System.Data.DataRowView in combobox - c#

I am just Trying to insert the data into the Sql From Selecting the item From the combobox in windows form.
But after the insertion in the database is does not show the value of selected item but it shows ("System.Data.DataRowView").
my code of insertion Is.
FORM LOAD-
SqlDataAdapter adp = new SqlDataAdapter("select * from CPP", con);
DataSet ds= new DataSet();
adp.Fill(ds);
comboBox10.DisplayMember = "Name";
comboBox10.ValueMember = "Id";
comboBox10.DataSource = ds.Tables[0];
On the BUTTON CLICK EVENT-
SqlCommand cmd = new SqlCommand("Insert into CPP (Name) values ('" + comboBox10.SelectedItem.ToString() + "')", con);
cmd.ExecuteNonQuery();
After the insertion of selective item.
It Shows In the database Table-("System.Data.DataRowView")
Any suggestion?

You can try below updated code.
var row = (DataRowView)comboBox10.SelectedItem;
SqlCommand cmd = new SqlCommand("Insert into CPP (Name) values ('" + row["Name"].ToString() + "')", con);
cmd.ExecuteNonQuery();

You need to set DisplayMember and ValueMember properties accorrdingly.
ComboBox1.DisplayMember = "Foo";
ComboBox1.ValueMember = "Bar";
If you don't specify these properties, a ListControl like ComboBox does not know what to display. So it displays just the type of the item as string (Type.FullName).

Related

Add referenced name instead of ID from comobox

I have 2 tables. First has column (categoryID) that is foreign key for categoryID in second table.Second table has 2 columns (categoryID, categoryName). After bit struggling I've displayed in combobox categoryName instead of categoryID. But now when I want to choose from existing categoryName that is already created (displayed in dropdown in combobox), is not possible because I have to type there int not string format. I'm beginner in programming
con.Open();
string cmddt = "insert into wallettbl(sum, date, categoryID, type)
values ('" + textBox1.Text + "','" + textBox2.Text + "','" +
comboBox1.Text + "', '" + type + "')";
SqlCommand com = new SqlCommand(cmddt, con);
com.ExecuteNonQuery();
How to write code if I want to add string (from combobox) instead of int, but in first table will be added categoryID which is referenced to categoryName.
EDIT: added code for combobox
con.Open();
string cmddt = "select categoryNAME from categoryTbl";
SqlCommand com = new SqlCommand(cmddt, con);
SqlDataAdapter da = new SqlDataAdapter(cmddt, con);
DataSet ds = new DataSet();
da.Fill(ds);
com.ExecuteNonQuery();
con.Close();
change the query to load the categories as below:
string cmddt = "select categoryID, categoryNAME from categoryTbl";
Set the datasource for comboBox1 as below:
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "categoryNAME";
comboBox1.ValueMember = "categoryID";
and finally modify the code to insert data into the wallettbl as follows:
string cmddt=
#"INSERT INTO WALLETTBL(sum, date, categoryID, type)
VALUES (#Sum, #Date, #CategoryId, #Type);";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add("#Sum", SqlDbType.Int).Value = textBox1.Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = textBox2.Text;
cmd.Parameters.Add("#CategoryId", SqlDbType.Int).Value = Convert.ToInt32(comboBox1.SelectedValue);
cmd.Parameters.Add("#Type", SqlDbType.Varchar).Value = type;
await conn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}

Using Drop-down with Check-boxes in Asp.net

I have 2 drop-down boxes and i want the first drop-down to filter the 2nd one like cascading so the first one has check-boxes and i want to pass the selected items from the first one to the 2nd but getting a "syntax error". I run it into debug mode and the output result looks like this
CommandText "select id, name FROM myTable where id in (''CKU019','CW5036'') "
and it seems there is extra apostrophe near CKU019. Here is my code
protected void bindDDL()
{
string selectedValues = string.Empty;
foreach (ListItem item in ddchkCountry.Items)
{
if (item.Selected)
selectedValues += "'" + item.Value + "',";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in ('" + selectedValues + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
facDDL.DataSource = ds;
facDDL.DataTextField = "name";
facDDL.DataValueField = "id";
facDDL.DataBind();
}
Remove the extra ' wrapping your selected values...
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in (" + selectedValues + ")", con);

Not able to fill combo box dynamically in c#.net

i am writing the below code to get the data in the combo box but it does not show any data in the combo box so please help..... below is my code for filling combo box..
string qry = "select ctid,city from city order by city";
cmd = new SqlCommand(qry, con);
ds.Clear();
ad = new SqlDataAdapter(qry,con);
ad.Fill(ds);
MessageBox.Show(ds.Tables[0].Rows[1]["city"].ToString());
comboBox1.DataSource = ds.Tables[0];
comboBox1.DisplayMember = "city";
comboBox1.ValueMember = "ctid";
in the messagebox after the ad.fill(ds) i can see the value inside the table but it is not reflecting in the combo box...
I have used the same logic in my app just the difference was to specify the CommandType property as 'Text' and CommandText property as the query, in SqlCommand.
var sqlDs = new DataSet();
var sqlComm = new SqlCommand();
sqlComm.Connection = sqlCon;
sqlComm.CommandType = CommandType.Text;
sqlComm.CommandText = query;
sqlDa = new SqlDataAdapter(sqlComm);
sqlDa.Fill(sqlDs);
Also when you are specifying the display member and Value member then no need to specify the columns in select query, it still work. only for the performance basis you can specify the columns name.

getting a single databse value into text box

I would really appreciate if there is any reference to show in how i could transfer value from database into textbox. This my code for combobox, but instead of combobox i would like in textbox
OleDbDataAdapter oda = new OleDbDataAdapter("select subject_name from subjecti where subject_name = '" + comboBoxSubjectName.Text + "'", con);
DataTable dt = new DataTable();
oda.Fill(dt);
comboBoxSubjectCodeUpdate.DataSource = dt;
comboBoxSubjectCodeUpdate.DisplayMember = "subject_name";
You can try something like this
string myquery = "SELECT MyColumn FROM MyTable";
using (var command = new OleDbCommand(myquery, connection))
{
MyTextBox.Text = command.ExecuteScalar().ToString();
}
Please note if you will be returning multiple values then I suggest you use ExecuteReader() as ExecuteScalar() only returns a single value.

How to bind grid view data based on the dropdown list selected value

I have one drop down list to select student name.when i select a student name in the drop down list, grid view has to show details of selected name.
This is my coding for this but it didn't display anything.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
this is my cs code to get the details of selected value.But it didn't any thing.
VALUE is a reserved keyword for T-SQL. Use it with square brackets like [VALUE]
And please use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
SqlCommand cmd = new SqlCommand("SELECT [VALUE], VDESC FROM CSOPTFD WHERE OPTFIELD = 'WONO' AND [VALUE] LIKE '%' + #value + '%'", con);
cmd.Parameters.AddWithValue("#value", customerddl.SelectedValue);
Have you bind Dropdown Correctly,like CustomerId , Text and after that are you calling this code from Selected_Index_Changed Event with PostBack True ?
Try providing the code in a try - catch block. Use the finally block to closed the connection by using con.Close();
Also try closing the connection and then accessing the dataset for values.
SqlConnection con =null;
DataSet ds=null;
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["MGLCOMConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT VALUE,VDESC FROM CSOPTFD WHERE OPTFIELD='WONO'AND VALUE LIKE '%" + customerddl.SelectedValue + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
}
catch(SQLException ex)
{
}
finally
{
if(con!=null)
con.Close();
}
GridView1.DataSource = ds;
GridView1.DataBind();

Categories

Resources