Sam Okeh

Sam Okeh

  • NA
  • 114
  • 0

How to add an item to combobox if no item found?

May 14 2019 9:56 AM

Greetings experts, 

We have a database called Types that has two fields, TypeID, and Type Name.

Then we have a textbox called newType.
The idea of this textbox is that when a user attempts to select an item from the combobox and that item does not exist in the combobox, then enter the new item into the newType textbox and submit to the database.
Once submitted, it now becomes available for selection in the combobox.
Here is how I have approached this problem:

 

  1. //Populate Combobox1  
  2. SqlDataAdapter sda1 = new SqlDataAdapter("SELECT DISTINCT TypeId, TypeName FROM Types", constr);  
  3. //Fill the DataTable with records from Table.  
  4. DataTable dt = new DataTable();  
  5. sda1.Fill(dt);  
  6.   
  7. //Insert the Default Item to DataTable.  
  8. DataRow row = dt.NewRow();  
  9. row[0] = 0;  
  10. row[1] = "Please select member";  
  11. dt.Rows.InsertAt(row, 0);  
  12. //Assign DataTable as DataSource.  
  13. txtType.DataSource = dt;  
  14. txtType.DisplayMember = "TypeName";  
  15. txtType.ValueMember = "TypeId";  
  16. txtType.SelectedIndex = 0;  

Once a value has been entered into the newType textbox field, I process it:  

  1. //check if this is new type and insert into Types table  
  2. if (mID <= 0)  
  3. {  
  4. SqlCommand cmd = new SqlCommand("insert into Types(TypeName) VALUES(@typeName)SELECT SCOPE_IDENTITY()", con);
  5.   
  6. cmd.CommandType = CommandType.Text;
  7. cmd.Parameters.AddWithValue("@typeName", txtTypeName.SelectedItem);  
  8.                    
  9. con.Open();  
  10. //get the newly inserted ID - to be used later  
  11. int typeid = Convert.ToInt32(cmd.ExecuteScalar());  
  12. con.Close();  
  13.   
  14. if (typeid != 0)  
  15. {  
  16. MessageBox.Show("Record Saved Successfully");  
  17. }  
  18.    
  19. //insert new typeid along with other fields into Transactions table  
  20.    …  
  21.    ...
The problem is when I click submit to add the newType to the database, I am getting the following error message:
 
 System.ArgumentException: No mapping exists from object type System.Data.DataRowView to a known managed provider native type.
at System.Data.SqlClient.MetaType.GetMetaTypeFromValue(Type dataType, Object value, Boolean inferLen, Boolean streamAllowed)
 
Any ideas what I am doing wrong?
 
Thanks in advance 

Answers (7)