如何在组合框中显示2列?(多个值)
本文关键字:2列 显示 组合 | 更新日期: 2023-09-27 17:52:13
现在我有这个:
da = new SqlDataAdapter("SELECT * FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"]);
}
现在它只显示klantId
,但我还想显示名称。当我有了klantId
和名称我怎么能只选择klantId
呢当我输入
selectedUserId = combobox.Text;
编辑://这是我初始化组合框的地方
da = new SqlDataAdapter("SELECT (kg.voornaam+' '+kg.achternaam + ' - ' + CONVERT(varchar,l.klantId)) AS dispValue FROM LOGIN l inner join klantGegevens kg on l.klantId=kg.klantid WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "dispValue";
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
//这是删除用户的按钮
private void btnDeleteUser_Click(object sender, EventArgs e)
{
if (userInformation.addPersonsPermission)
{
int selectedUserId = Convert.ToInt32(((DataRowView)txtKlantid.SelectedValue)["klantId"]);
if (users.deleteKlantAdmin(selectedUserId))
{
MetroMessageBox.Show(this, "Gebruiker "+selectedUserId+" is verwijderd", "Verwijderd");
}
else
{
MetroMessageBox.Show(this, "Er ging iets fout, contacteer de beheerder", "Fout");
}
}
else
{
loginAddUser addUserLogin = new loginAddUser();
addUserLogin.ShowDialog();
}
}
可以使用ComboBox的DisplayMember
和ValueMember
属性
da = new SqlDataAdapter("SELECT * FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "Name"; //Name of field to display
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
你可以得到Name
和Id
通过执行
var name = txtKlantid.Text;
var id = txtKlantid.SelectedValue;
根据您的要求,您可以组合Id和Name
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"].ToString()+"-"+dtt.Rows[i]["Name"].ToString());
}
DisplayMember
和ValueMember
属性在这种情况下将是您的朋友。
请避免选择表中的所有字段来填充您的组合框。你可以这样写,
da = new SqlDataAdapter("SELECT (name + ' - ' + CONVERT(varchar,klantId)) AS dispValue, klantId FROM LOGIN WHERE RECHTEN=2", conn);
dtt = new DataTable();
da.Fill(dtt);
txtKlantid.DisplayMember = "dispValue";
txtKlantid.ValueMember = "klantId";
txtKlantid.DataSource = dtt;
在这个例子中,txtKlantid.SelectedValue
会给你klantId
的值,txtKlantid.Text
会给你name - klantId
的值。