如何在组合框中显示2列? (多个值)

时间:2015-06-02 09:59:55

标签: c# combobox

现在我有这个:

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();
            }
        }

2 个答案:

答案 0 :(得分:2)

您可以使用ComboBox的DisplayMemberValueMember属性

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;

您可以通过以下

返回NameId
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)

在这种情况下,

DisplayMemberValueMember属性将是您的朋友。

请避免从表格中选择所有字段以填充您的组合框。你可以做点什么,

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值。

希望这会有所帮助......