我有一个下拉列表。我需要绑定两个数据表值字段 这里
ddlitem.datasource= dtitem
ddlitem.datatextfield = dtitem.cloumn["name"].tostring()+"-"+dtitem.cloumn["tagname"].tostring()
我这样做我在这里得到例外。如何在下拉列表中组合列值
当我检索下拉列表的选定值时
我应该只获得此列值的值:dtitem.cloumn["name"].tostring()
string stritem= ddlitem.selecteditem.Text.Tostrigng();
那么如何分割字符串的值?
答案 0 :(得分:2)
您需要迭代其中一列的行,并且需要将您的项目设置为整列
编辑:
应该像......
for (int count = 0; count < dtitem.Rows.Count; count++)
{
dtitem.Rows[count]["name"] = dtitem.Rows[count]["name"].tostring() + "-" + dtitem.Rows[count]["tagname"].tostring();
}
答案 1 :(得分:2)
我认为dtitem
是DataRow
个对象。我建议你创建一个字典对象并填写它
Dictionary<string,string> dicts = new Dictionary<string,string>();
foreach(DataRow row in dt.Rows)
{
string key = row["name"].ToString();
string val = String.Format("{0}-{1}",row["name"],row["tagname"]);
}
然后将其绑定到下拉列表
dropdown.DataSource = dicts;
dropdown.DataValueField = "Key";
dropdown.DataTextField = "Value";
dropdown.DataBind();
当您获得dropdown.SelectedValue
时,它已经是name
,因此您无需将其与tagname
答案 2 :(得分:1)
DropDownList.DataTextField仅适用于您绑定到它的对象的列/字段。如果需要显示倍数值,可以选择以下选项:
答案 3 :(得分:1)
尝试使用以下内容:
public void Populate_DriverDropDown()
{
//Opening and closing connection not required while using SqlDataAdapter
//sql command to select the drivers and their ids (displaying both the drivername and firstSurname)
String sqlQuery = "SELECT driverID, nameDriver+' '+firstSurname AS driverFullname FROM driver ORDER BY driverID ASC";
//end
//using SqlDataAdapter and DataSet
SqlDataAdapter Da = new SqlDataAdapter(sqlQuery, DBConn);
DataSet Ds = new DataSet();
Da.Fill(Ds, "driver");
if (Ds.Tables[0].Rows.Count > 0)
{
//populating each dropdown row with driver name and id.
foreach (DataRow Dr in Ds.Tables[0].Rows)
{
VehicleDriver.Items.Add(new ListItem(Dr["driverFullname"].ToString(), Dr["driverID"].ToString()));
}
}
//to have select option at the top of the dropdown list
VehicleDriver.Items.Insert(0, "Select a driver");
}
答案 4 :(得分:0)
Dictionary<string,string> dicts = new Dictionary<string,string>();
foreach(DataRow row in dt.Rows)
{
string key = row["name"].ToString();
string val = String.Format("{0}-{1}",row["name"],row["tagname"]);
}
请重写
Dictionary<string,string> dicts = new Dictionary<string,string>();
foreach(DataRow row in dt.Rows)
{
string key = row["name"].ToString();
string val = String.Format("{0}-{1}",row["name"],row["tagname"]);
dicts.Add(key, val);
}