现在我有这个:
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;
编辑:
//这就是我最初的COMBOBOX
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();
}
}
答案 0 :(得分:2)
您可以使用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和名称
for (int i = 0; i < dtt.Rows.Count; i++)
{
txtKlantid.Items.Add(dtt.Rows[i]["klantId"].ToString()+"-"+dtt.Rows[i]["Name"].ToString());
}
答案 1 :(得分:1)
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
值。
希望这会有所帮助......