How do you change specific data in a datatable column? - c#

I've populated a DataTable with a DataAdapter but I would like to change the values dynamically for all of the rows in that column in the DataTable. How do I go about doing this?
Here is my current code:
SqlConnection conn = null;
string sSQL = "";
string connString = "Datasourceetc";
sSQL = "SELECT TEST_ID FROM TEST_TABLE";
SqlDataAdapter sda = new SqlDataAdapter(sSQL, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
dt.Columns["TEST_ID"] = "changed"; //Not changing it?!
}
GridView1.DataSource = dt;
GridView1.DataBind();
Thanks

Everything above looks good except when iterating through the rows you can access the columns like so...
foreach (DataRow row in dt.Rows)
{
row["ColumnName"] = "changed"; //Not changing it?!
}

You need to fill first, then change!
SqlConnection conn = new SqlConnection(connString);
string sSQL = "SELECT TEST_ID FROM TEST_TABLE";
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(sSQL, conn);
// fill the DataTable - now you should have rows and columns!
sda.Fill(dt);
// one you've filled your DataTable, you should be able
// to iterate over it and change values
foreach (DataRow row in dt.Rows)
{
row["TEST_ID"] = "changed"; //Not changing it?!
}
GridView1.DataSource = dt;
GridView1.DataBind();
Marc

Related

edit datatable or add combobox 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";

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;
}

Add hyperlinks to datatable

I would like to add hyperlinks dynamically to the cell of a specific column in my datatable. Currently my code is only showing the text.
Here is my code:
SqlConnection conn = null;
string sSQL = "";
string connString = "Datasourceetc";
sSQL = "SELECT TEST_ID FROM TEST_TABLE";
SqlDataAdapter sda = new SqlDataAdapter(sSQL, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
row["TEST_ID"] = "<a href='www.google.com'>Google</a>"; //<----I only see the text!
}
GridView1.DataSource = dt;
GridView1.DataBind();
Thank you
If you're doing this through an asp:BoundField you'll want to set the HtmlEncode property to false.

Categories

Resources