循环通过动态创建的列表框

时间:2012-07-18 14:22:17

标签: c# asp.net

我正在处理导出数据,现在一些字段导出值而不是文本。所以我保存了将文本和值返回到列表框的对象,并将其与对象的列表框中的值相匹配,如下所示:

MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataBind();

string materialString = "";


foreach (ListItem i in listBoxMaterials.Items)
{
    if (i.Value == row["MaterialTypeID"].ToString())
    {
        materialString = i.Text;
    }
}

当我将它用于i.Value时,它总是返回“System.Data.DataRowView”而不是实际值。我在代码背后做了这一切。无论如何围绕这个让它工作?

谢谢!

1 个答案:

答案 0 :(得分:3)

您需要设置DropDownList的DataTextField和DataValueField属性。例如:

MaterialDB materials = new MaterialDB();
DropDownList listBoxMaterials = new DropDownList();
listBoxMaterials.DataSource = materials.GetItems(ModuleId, TabId);
listBoxMaterials.DataTextField = "MaterialName";
listBoxMaterials.DataTextValue = "MaterialID";
listBoxMaterials.DataBind();

string materialString = "";    

foreach (ListItem i in listBoxMaterials.Items)
{
    if (i.Value == row["MaterialTypeID"].ToString())
    {
        materialString = i.Text;
    }
}