我有这个组合框从SQL获取值:
public void brandSelectCB(ComboBox cb)
{
string sSQL = " SELECT" +
" id, name" +
" FROM" +
" tbBrand" +
" ORDER BY" +
" name";
sqlConnect connect = new sqlConnect();
DataTable dt = new DataTable();
dt = connect.getBD(sSQL);
cb.DataSource = dt;
cb.DisplayMember = "name";
cb.ValueMember = "id";
}
我还有一个像这样的列表视图:
public void modelSelect(ListView lvModel)
{
string sSQL = " SELECT" +
" tbModel.id, tbBrand.name AS brand, tbModel.name" +
" FROM" +
" tbBrand, tbModel" +
" WHERE" +
" tbBrand.id = tbModel.brand" +
" ORDER BY" +
" tbBrand.name, tbModel.name";
sqlConnect connect = new sqlConnect();
DataTable dt = new DataTable();
dt = connect.getBD(sSQL);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["id"].ToString());
item.SubItems.Add(dr["brand"].ToString());
item.SubItems.Add(dr["name"].ToString());
lvModel.Items.Add(item);
}
}
当我从列表视图中选择一行并单击编辑按钮时,它应该将所选行的值从相应的组合框和文本框中获取:
private void btnEdit_Click(object sender, EventArgs e)
{
this.txtID.Text = lvModels.SelectedItems[0].SubItems[0].Text;
this.cbBrand.SelectedText = lvModels.SelectedItems[0].SubItems[1].Text;
this.txtName.Text = lvModels.SelectedItems[0].SubItems[2].Text;
}
但我在组合框中没有得到任何值,只在文本框中。我意识到这是因为组合是以下拉列表样式,我应该使用SelectedValue
或SelectedItem
,但它们似乎都不起作用。
有什么想法吗?
答案 0 :(得分:0)
您可以尝试这样的事情:
string brandText = lvModels.SelectedItems[0].SubItems[1].Text;
DataRow itemToSelect = ((DataTable) this.cbBrand.DataSource)
.Rows
.Cast<DataRow>()
.FirstOrDefault(r=>r.Field<string>("name").Equals(brandText));
if(itemToSelect != null)
cbBrand.SelectedItem = itemToSelect;
免责声明:我没有对此进行测试;这是来自记忆。
如果你在ListViewItem
的某处隐藏BrandID,这会更简单:那么你可以使用SelectedValue
。