Unable to get GRIDVIEW when new column added - c#

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

Related

Could not show content of a table in SQL server to C# Gridview

I want to show content of a table("newexample") in my database in SQL server to gridview in ASP.net, but the gridview shows nothing. How to fix it?
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string cs = ConfigurationManager.ConnectionStrings["SampleDBCS"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("select * from newexample", con);
DataTable dt = new DataTable();
dt.Columns.Add("col0");
dt.Columns.Add("col1");
dt.Columns.Add("col2");
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
DataRow dr = dt.NewRow();
dr["col0"] = rdr["col0"];
dr["col1"] = rdr["col1"];
dr["col2"] = rdr["col2"];
dt.Rows.Add(dr);
}
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Did you get any exception? Try moving con.Close() after DataBind() and see how it goes.
Try to use the code below:
DataSet dataSet = new DataSet("newexample");
SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from newexample", connectionString);
dataAdapter.Fill(dataSet);
if (dataSet != null)
{
if (dataSet.Tables[0].Rows.Count != 0)
{
GridView1.DataSource = dataSet ;
GridView1.DataBind();
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}
}
This is a better approach since SqlDataAdapter will take care for SqlConnection. It is responsible to create the connection and to close it at the end of operation in the best way possible.
This is not a tested code so if you have any problem let me know..

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.

Bind DataTable to Datagridview that already have column defined into data grid

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 Datagridview 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 solve the error here
you can just define an empty datatable without defining columns from your datagridview to it
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;

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

How do you change specific data in a datatable column?

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

Categories

Resources