edit datatable or add combobox c# - c#

this code in c# windows forms populate my combobox with data of mysql database, and he work
conn.Open();
string query = "SELECT * FROM FRUITS";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.ValueMember = "NAME";
comboBox1.DisplayMember = "NAME";
But, i need one of two options:
Add a row in FIRST POSITION of combobox.
Add a row in FIRST POSITION of dataTable.
example: this code return to me a combobox with values "Banana" and "Apple" but i need the first value is "Select one Fruit".
if i using the next code after "da.Fill(dt)", he add a row in dataTable and appear in combobox, BUT after the "Apple", combobox=("Banana", "Apple", "Select one Fruit") but i need ("Select one fruit", "Banana", "Apple")
dt.Rows.Add("Select One Fruit");
How i can do this?

Try it.
ComboBox
combobox1.Items.Insert(0, "Select a fruit");
DataTable
dt.Rows.InsertAt(row,0);

I think you're looking for
dt.Rows.InsertAt
http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.insertat.aspx
OR
combobox1.Items.Insert
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.objectcollection.insert.aspx

You can't insert item into a comboBox, when DataSource property is in use. you got an exception: "Items collection cannot be modified when the DataSource property is set.".
But if you add a new row at 0 index to dataTable before you set it as a datasource it works well
conn.Open();
string query = "SELECT * FROM FRUITS";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//Add new row
DataRow row = dt.NewRow();
row["NAME"] = "Select a fruit";
dt.Rows.InsertAt(row, 0);
comboBox1.DataSource = dt;
comboBox1.ValueMember = "NAME";
comboBox1.DisplayMember = "NAME";

Related

C# with SQL: Populating multiple comboboxes each with different columns of same table

as stated in the title, I would appreciate some help with populating comboboxes with different columns of the same table
I don't have the actual source codes with me but I was able to populate one combobox with something like
SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt;
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
but I have 5 comboboxes, and I didn't want to repeat the same blocks of code 5 times just for that. so I looked around and found some answers, including changing datasource to bindingsource, like so:
myCMB.DataSource = new BindingSource(da, "Column_Name");
but doing so would populate the combobox with each letter of the first item of the specified column (ie. if the first item in "Column_Name" is ABCD, my combobox options would be A,B,C,D)
So, I tried looking for more answers but I can't find any. is there a more efficient way of populating my comboboxes or do I really have to repeat essentially the same lines of code for each of them? if anyone can help, it would be greatly appreciated.
Use a copy of the datatable:
SqlDataTable dt = new SqlDataTable();
SqlCommand comm = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
da.Fill(dt);
myCMB.DataSource = dt.Copy();
myCMB.DisplayMember = "display";
myCMB.ValueMember = "value;
Try this:
DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Display");
string query = #"SELECT ID AS ID, Description AS CODE FROM [Tender] ORDER BY ID";
SqlDataReader sqlReader = new SqlCommand(query, DB.SQLConnection).ExecuteReader();
while (sqlReader.Read())
{
if (!string.IsNullOrEmpty(sqlReader["CODE"].ToString()))
dt.Rows.Add(sqlReader["ID"].ToString(), sqlReader["CODE"].ToString());
}
cbPayment1.DisplayMember = "display";
cbPayment1.ValueMember = "value";
cbPayment1.DataSource = dt;

Retrive Names from table with age above 20 and display them in listBox

I have difficulties with my program. i have a dataGridView filled with values from my access database.I also have a listBox just placed under the dataGridView.In my dataGridView i have name_Columns,Contact,age,status etc.The difficulties i have is , to display in the list box the names of people with age above 20 only so i don't know how to do that.I will be very happy for any assistance from you.I've inserted an image and some code I've already done.
thanks
private void button1_Click(object sender, EventArgs e) //View items in the Data Grid
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string query = "select * from DataPay";
cmd.CommandText = query;
DataTable dt = new DataTable();
OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
adap.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
You forgot to add the condition WHERE clause like
string query = "select * from DataPay where Age > 20";
You can use the RowFilter property of the DataView. You can set this property directly on the DataTable retrieved but this will also filter the DataGridView. If you want to keep the two controls separated with separated content then you can create a new DataView using the original table as source of data for the new DataView
....
DataTable dt = new DataTable();
OleDbDataAdapter adap = new OleDbDataAdapter(cmd);
adap.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
DataView dv = new DataView(dt, "Age > 20", "Name", DataViewRowState.CurrentRows);
listBox.DisplayMember = "Name";
listBox.DataSource = dv;
}

Unable to get GRIDVIEW when new column added

This is my SEARCH Function with gridview.I'm not able to get gridview in Form remaining all are fine.Here i added new columns two.Please help me out.thanks
private void txtSearch02()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("select ItemCode,ItemName,PointsNeeded from tb_ItemRedemption where (ItemCode is null or ItemCode='" + txtkey2.Text.Trim() + "') or (ItemName is null or ItemName='" + txtkey2.Text.Trim() + "')", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["ItemCode"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
con.Close();
dt.Columns.Add("Quantity");
dt.Columns.Add("TotalPoints");
// for caliculation
txtPointsNeeded.Text = dt.Rows[0]["PointsNeeded"].ToString();
//dt.Rows[0]["Quantity"].ToString();
//dt.Rows[0]["TotalPoints"].ToString();
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
// for caliculation
txtGetQuantity.Text = txtQuantity.Text;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
}
Following on from my comments regarding parameterising the query and using the 'using(){}' statement I'd start by writing something like this:
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(myStr))
{
string sql = "select ItemCode,ItemName,PointsNeeded from tb_ItemRedemption where (ItemCode is null or ItemCode = #txtkey2) or (ItemName is null or ItemName = #txtkey2)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#txtkey2", txtkey2.Text.Trim());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//You're currently adding a blank DataTable to a session variable below as you've not
//filled it yet. I've left this incase that's what you meant to do.
Session["ItemCode"] = dt;
con.Open();
//SqlDataAdapter should be able to fill a DataTable as well as a dataset.
sda.Fill(dt);
if (dt.Rows.Count > 0) //Put a breakpoint here to check if anything is returned in dt
{
dt.Columns.Add("Quantity");
dt.Columns.Add("TotalPoints");
// for caliculation
txtPointsNeeded.Text = dt.Rows[0]["PointsNeeded"].ToString();
//Not sure what you're trying to do here. You're just adding a blank row to dt.
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
// for caliculation
txtGetQuantity.Text = txtQuantity.Text;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
}
else
{
//Code to handle nothing being returned.
}
}
If you have previous three columns (with bindvalue) and add other two columns, It would be confusing one for it.
Add all the columns to datatable again. means three and new two.
Try it. It should work.cause your code is right.
Make Sure your Auto Generated Columns is set to 'true'.
Go to properties of grid view, and change auto generated columns to true in case of false.
Go through the links for further clarification : Click here

Error :Cannot Find Table 0

I am seeing an error regarding cannot find table 0, where the dataset doesn't contain the table data. This is my code to fetch rows from a table:
DataTable dt = new DataTable();
SqlConnection sqlconnection;
sqlconnection = new SqlConnection(#"connectionstring");
sqlconnection.Open();
string sql = "Select (supplier_id,name) from supplier_info where supplier_id= '"+supplierid+"'";
SqlCommand cmd = new SqlCommand(sql, sqlconnection);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dtset = new DataSet();
adpt.Fill(dt);
dt = dtset.Tables[0];
DataRow dr;
dr = dt.Rows[0];
sqlconnection.Close();
return dr;
Business logic code:
Cust_datalogic dc = new Cust_datalogic(); //datalogic class
DataTable dt = new DataTable();
DataRow dr;
dr=dc.GetSupplierInfo(id); //method
Supplier_BLL bc = new Supplier_BLL(); //business logic class
bc.Ssup_ID = dr[0].ToString();
bc.Ssup_name = dr[1].ToString();
return bc;
Your problem area in your code is
adpt.Fill(dt); //You are filling dataTable
dt = dtset.Tables[0]; // You are assigning Table[0] which is null or empty
Change it to
adpt.Fill(dtset); //Fill Dataset
dt = dtset.Tables[0]; //Then assign table to dt
OR
Your can directly use SqlDataAdapter to Fill DataTable thus no need of DataSet.
Just remove DataSet, use
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
DataRow dr = dt.Rows[0];
I had this issue when calling to web service method. Issue was with the filter / Query condition. What I was looking for it was not exist in the database. So, check if the required data exists in database.
Another way is to add a select statement after the insert query.

fill data to already defined columns in datagridview

i am trying to Bind DateTable to Datagridview that already have columns designed using Designer in VS. Source for DataTable is sql database. I am trying to do this using following code which adds only blank rows in datagridview. also i update the DataPropertyName property of a DGV column with the name of the column in the DataTable
SqlConnection CN = new SqlConnection(mysql.CON.ConnectionString);
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.Name);
col.DataPropertyName = col.Name;
}
SqlDataAdapter sda = new SqlDataAdapter("select id,name,age,notes from test where id = '" + txtID.Text + "'", CN);
sda.Fill(dt);
dataGridView1.DataSource = dt;
please nead help to know why the rows are viewed empty with out data
i think your sda.Fill(dt); is wrong, because according to reference on SqlDataAdapter you may need fill DataSet no DataTable. Look and learn more about how to get data from database. Try any tutorials rather than you ask on stackoverflow.
http://msdn.microsoft.com/en-us/library/ms171920.aspx
http://msdn.microsoft.com/cs-CZ/library/system.data.sqlclient.sqldataadapter.aspx
Modify your code a little bit:
SqlConnection CN = new SqlConnection(mysql.CON.ConnectionString);
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select id,name,age,notes from test where id = '" + txtID.Text + "'", CN);
sda.Fill(dt);
dataGridView1.DataSource = dt;
for (int i = 0; i<dataGridView1.Columns.Count;i++)
{
dataGridView1.Columns[i].DataPropertyName = SelectionChangeCommitted.Columns[i].ColumnName;
}

Categories

Resources