简体   繁体   中英

How to get values from BindingSource in C#

I am working with WinForm in this i have 3 RadioButton one ComboBox and have three BindingSource

I want that when I check any of the RadioButton s, the values from the particular DataSources get bound to the ComboBox's ValueMember and DisplayMember .
The program has a SQL query where I want to send value based on the checked radio button.

private void rdbMed_CheckedChanged(object sender, EventArgs e)
{
    cmbStock.DataSource = null;
    cmbStock.DataSource = this.medicinesBindingSource;
    this.cmbStock.DisplayMember = ""; //i want to bind "Med_ID" from medicinesBindingSource
    this.cmbStock.ValueMember = "";  //"Med_Name"

}

private void rdbCat_CheckedChanged(object sender, EventArgs e)
{
    cmbStock.DataSource = null;
    cmbStock.DataSource = this.categoriesBindingSource;
    this.cmbStock.DisplayMember = ""; //"category_Name"
    this.cmbStock.ValueMember = ""; // category_ID"
}

private void rdbPharm_CheckedChanged(object sender, EventArgs e)
{
    cmbStock.DataSource = null;
    cmbStock.DataSource = this.pharmaceuticalBindingSource;
    this.cmbStock.DisplayMember = "";// "Pharma_Name"
    this.cmbStock.ValueMember = "";// "Pharma_ID"
}

Bellow are the parameter of the Query. It will help you to understand what I want to achieve.

if (rdbMed.Checked)
{
    con.cmd.Parameters.AddWithValue("@Med_ID", cmbStock.ValueMember);
    con.cmd.Parameters.AddWithValue("@category_ID", "");
    con.cmd.Parameters.AddWithValue("@Pharma_ID", "");
}
else if (rdbCat.Checked)
{
    con.cmd.Parameters.AddWithValue("@Med_ID", "");
    con.cmd.Parameters.AddWithValue("@category_ID", cmbStock.ValueMember);
    con.cmd.Parameters.AddWithValue("@Pharma_ID", "");
}
else if (rdbPharm.Checked)
{
    con.cmd.Parameters.AddWithValue("@Med_ID", "");
    con.cmd.Parameters.AddWithValue("@category_ID", "");
    con.cmd.Parameters.AddWithValue("@Pharma_ID", cmbStock.ValueMember);
}

Easiest and the least pain way of doing this is resolving it inside SQL command and way to do it is cast your columns with AS VM and AS DM and make your DisplayMember = "DM" and ValueMember = "VM" , so if you have sql query like SELECT USERID AS VM, NAME AS DM or SELECT PRODUCTID AS VM, NAME AS DM it will both work.

Problem later is if you do something with code and you may make mistakes trying to get USERID from databinding but it is instead VM . To avoid this you could "double select" values in query like SELECT USERID, NAME, ...., USERID AS VM, NAME AS DM this way you will have VM and DM for your controls but still hold original columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM