Click here to Skip to main content
16,021,687 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
C#
I have ComboBox, populate with Database.. with Read Method..
string sql = "Select miscCode,miscDesc from miscMaster ";
              // sql = sql + "WHERE miscCategory='Hundai' ";
               sql = sql + "ORDER BY miscDesc";
               //cn.Open();
               cmd = new SqlCommand(sql, cn);
               dr = cmd.ExecuteReader();
               cmb_makeCode.Items.Clear();
               cmb_makeCode.Items.Add("-- Select --");
               while (dr.Read() != false)
               {
                   cmb_makeCode.ValueMember = dr[0].ToString();
                   cmb_makeCode.Items.Add(dr[1].ToString());
                   cmb_makeCode.DisplayMember = dr[0].ToString();
               }
               cn.Close();


But when I want to store the value of 'miscCode' into a string varibale in below code give an error: "Unable to cast object of type 'System.String' to type 'System.Data.DataRowView'."

C#
private void cmb_makeCode_SelectedIndexChanged(object sender, EventArgs e)
       {
          DataRow selectedDataRow = ((DataRowView)cmb_makeCode.SelectedItem).Row;
          string mkcd = selectedDataRow["miscCode"].ToString();

           MessageBox.Show(mkcd);
}



plz help me ...
Posted
Comments
Jim Jos 9-Jul-12 6:10am    
When you are assigning to the combobox value you should assign the datarow rather than string.. then only you could cast it back to data row

The selecteditem of combobox will always be a string. Why do you want to make it as datarow. Make it as simple as below.
C#
private void cmb_makeCode_SelectedIndexChanged(object sender, EventArgs e)
       {
         
          string mkcd = cmb_makeCode.SelectedItem.ToString();

           MessageBox.Show(mkcd);
}
 
Share this answer
 
Comments
2pai 8-Jul-12 12:41pm    
Thanks But I want the DisplayMember value from combobox that i populate in previous code...
while (dr.Read() != false)
{
cmb_makeCode.ValueMember = dr[0].ToString();
cmb_makeCode.Items.Add(dr[1].ToString());
cmb_makeCode.DisplayMember = dr[0].ToString();
}
Then try this.

C#
private void cmb_makeCode_SelectedIndexChanged(object sender, EventArgs e)
       {

          string mkcd = cmb_makeCode.Text.ToString();

           MessageBox.Show(mkcd);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900