Reputation: 17
I have windows form project. I am using a combobox to populate some data from database. Combobox is displaying data from table correctly but the problem is when I am trying to get text value of selected text it display null value. here is the code
private void Form1_Load(object sender, EventArgs e)
{
loadCombobox("select designation, id from post order by id", txtDesignation, "designation", "id");
}
private void loadCombobox(string query, ComboBox name, string itemField, string valueField)
{
using(SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=FIR_db; User Id = sa; Password = 9889922527"))
{
try
{
SqlDataAdapter sda = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
sda.Fill(ds, "post");
name.DisplayMember = itemField;
name.ValueMember = valueField;
name.DataSource = ds.Tables["post"];
}
catch (SqlException exc)
{
DialogResult dr = MessageBox.Show("Error in server. Could not load Designation.", "Error in server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void txtDesignation_SelectedIndexChanged(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show(txtDesignation.SelectedText.ToString(), "Error in server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This project is on .net 4
Upvotes: 0
Views: 62
Reputation: 8782
What you want to access is comboBox.SelectedItem
property.
Edit:
From your comment it looks like you are populating the ComboBox
with DataRowView
objects. So, you probably have to get the value you are interested in from the row view. Try this:
dataRowView.Row["ColumnName"]
where the dataRowView
is your selected item from the ComboBox
. You may need to cast it to the DataRowView
.
Upvotes: 1
Reputation: 81610
SelectedText is just the highlighted portion of any text in the control.
Since you have the ValueMember set, try using the SelectedValue property instead.
Upvotes: 1