Im new in asp.net. I want to know how to add a row in a gridview programatically. I was able to do it but it just displays the latest addition.
Here is my code:
DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");
DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();
gvQnA.DataSource = dt;
gvQnA.DataBind();
Its because you are creating new table each time and binding it with the grid
Do code as below may resolve your issue ...
here i am taking existing datasource and binding it again by adding two more row...
DataTable dt = gridView.DataSource as DataTable;
if (dt != null)
{
DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
dt.AcceptChanges();
gvQnA.DataSource = dt;
gvQnA.DataBind();
}
#Pranay is correct.In addition You can also achive that by using DataTable as property.
private DataTable Dt
{
set { ViewState.Add("Dt", value); }
get { return (DataTable)ViewState["Dt"]; }
}
...
DataRow dr = Dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
Dt.Rows.Add(dr);
Dt.AcceptChanges();
gvQnA.DataSource = Dt;
gvQnA.DataBind();
You have added one row in your code thats why it is showing one row.
If you have added multiple rows it would have shown proper result
DataTable dt = new DataTable();
dt.Columns.Add("Question");
dt.Columns.Add("Answer");
DataRow dr = dt.NewRow();
dr["Question"] = txtQuestion.Text;
dr["Answer"] = txtAnswer.Text;
dt.Rows.Add(dr);
**DataRow dr = dt.NewRow();
dr["Question"] = "2nd row";
dr["Answer"] = "2nd row";
dt.Rows.Add(dr);**
dt.AcceptChanges();
gvQnA.DataSource = dt;
gvQnA.DataBind();
May be #Pranay is also right
Hey Just check this. This might help u
DataTable dataTable = new DataTable();
int columnsCount = // Set the number of the table's columns here.
for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
DataColumn dataColumn = new DataColumn();
// Assign dataColumn properties' values here ..
dataTable.Columns.Add(dataColumn);
}
int rowsCount = // Set the number of the table's rows here.
for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++)
{
DataRow dataRow = new DataRow();
dataRow["ColumnName"] = // Set the value here ..
dataTable.Rows.Add(dataRow);
}
Related
Why does SqlDataAdapter's Fill method not allow me to add a row with the same its own rows' value as appearance? I could not success to provide a row's value that appears at the same row with filled one in DataTable.
Check this out:
using (SqlDataAdapter a = new SqlDataAdapter("SELECT SIPNO, SERINO, TARIH FROM SNOHAREKETLER WHERE Cast(TARIH as DATE) BETWEEN '2015/03/19' AND '2015/03/20' AND (TEZNO = 'T23' OR TEZNO = 'T31') AND CIKTI is null", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
t.Columns.Add("MyColumn", typeof(string));
DataRow workRow;
int iGetCount = t.Rows.Count;
for (int i = 0; i <= iGetCount - 1; i++)
{
workRow = t.NewRow();
workRow["MyColumn"] = i;
t.Rows.Add(workRow);
}
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
Here is the solution of my issue. I searched and consulted someone. My issue was trying to add a NewRow and this causes the issue.
DataTable t = new DataTable();
a.Fill(t);
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
t.Columns.Add(newCol);
foreach (DataRow row in t.Rows)
{
row["NewColumn"] = "With String";
}
dataGridView1.DataSource = t;
I have a DataTable dt1 that contains this columns : PRODUCT_ID,MIN_VALUE,MAX_VALUE,AMOUNT
and another DataTable dt2 that contains this columns : ID,MIN,MAX,POINT_TO_ADD
dt1 contains multiple rows that I want to copy them to dt2 how can I do that ?
try this
foreach (DataRow sourcerow in dt1.Rows)
{
DataRow destRow = dt2.NewRow();
destRow["ID"] = sourcerow["PRODUCT_ID"];
destRow["MIN"] = sourcerow["MIN_VALUE"];
destRow["MAX"] = sourcerow["MAX_VALUE"];
destRow["POINT_TO_ADD"] = sourcerow["AMOUNT"];
dt2.Rows.Add(destRow);
}
Try this:
for(int i=0;i<dt1.Rows.Count;i++){
DataRow dr = dt2.NewRow();
dr["ID"] = dt1.Rows[i]["PRODUCT_ID"];
dr["MIN"] = dt1.Rows[i]["MIN_VALUE"];
dr["MAX"] = dt1.Rows[i]["MAX_VALUE"];
dr["POINT_TO_ADD"] = dt1.Rows[i]["AMOUNT"];
dt2.Rows.Add(dr);
}
I have multiple datatable. I want to show all the datatable rows into a single gridview.
How can I do that?
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
DataSet ds= new DataSet();
ds.Tables.Add(dtbag101);
ds.Tables.Add(dtwallet111);
GridView1.DataSource= ds;
GridView1.DataBind();
The column names for both datatable are the same.
Here I was trying to use dataset but only first DataTable i.e. datbag101 was showing in the gridview.
How can I show all the values in one gridview?
Provided that your two data tables have the same columns, you can UNION them with some handy LINQ.
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
var result = dtbag101.AsEnumerable().Union(dtwallet111.AsEnumerable());
GridView1.DataSource = result;
GridView1.DataBind();
Otherwise try use DataTable.Merge:
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111, true);
GridView1.DataSource = dtbag101;
GridView1.DataBind();
I'm not sure why this isn't working for you. Try this method (grabbed from here):
public static DataTable Union(DataTable First, DataTable Second)
{
//Result table
DataTable table = new DataTable("Union");
//Build new columns
DataColumn[] newcolumns = new DataColumn[First.Columns.Count];
for(int i=0; i < First.Columns.Count; i++)
{
newcolumns[i] = new DataColumn(
First.Columns[i].ColumnName, First.Columns[i].DataType);
}
table.Columns.AddRange(newcolumns);
table.BeginLoadData();
foreach(DataRow row in First.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
foreach(DataRow row in Second.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
table.EndLoadData();
return table;
}
Call the method with your two datatables:
GridView1.DataSource = Union(dtbag101, dtwallet111);
You can simply use DataTable.Merge method
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111); //Merge action
GridView1.DataSource= dtbag101;
GridView1.DataBind();
I dont know much about this. Just referred it now.
or else
try for loop
DataSet ds = new DataSet();
addTables(dtbag101);
addTables(dtwallet111); //ds will be merge of both tables here
private void addTables(DataTable dt)
{
for(int intCount = ds.Tables[0].Rows.Count; intCount < dt.Rows.Count;intCount++)
{
for(int intSubCount = 0;intSubCount < dt.Columns.Count; intSubCount++)
{
ds.Tables[0].Rows[intCount][intSubCount] = dt.Rows[intCount][intSubCount];
}
}
}
You may need to use DataTable.Merge
DataTable dtAll = new DataTable();
dtAll = dtbag101 .Copy();
dtAll.Merge(dtwallet111, true);
GridView1.DataSource= dtAll;
GridView1.DataBind();
Edit to show how it should work
private void BindGridWithMergeTables()
{
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("ID");
dt2.Columns.Add("ID");
DataRow dr1 = dt1.NewRow();
DataRow dr2 = dt2.NewRow();
dr1["ID"] = "1";
dr2["ID"] = "2";
dt1.Rows.Add(dr1);
dt2.Rows.Add(dr2);
DataTable dtAll = new DataTable();
dtAll = dt1.Copy();
dtAll.Merge(dt2, true);
dataGridView1.DataSource = dtAll;
dataGridView1.DataBind();
}
I have a datatable in windows form and I want to add a new row to the table. I always receive the error
Table doesn't have a primary key.
The question is that I don't want a primary key at all. It may have duplicated "ID" in the table.
My code:
using (DataTable dt = new DataTable())
{
dt.Columns.Add("EntryDE", typeof(string));
dt.Columns.Add("Descr", typeof(string));
dt.Columns.Add("Id", typeof(int));
foreach (DataGridViewRow row in dgv.Rows)
{
DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
if (check.Value != null)
{
if ((bool)check.Value)
{
//this row has a checkBox set to true (tick is added)
//add this row to dataTable ...
DataRow myRow = (row.DataBoundItem as DataRowView).Row;
DataRow dr = dt.NewRow();
dr["EntryDE"] = myRow["ID"].ToString();
dr["Descr"] = myRow["EntryName"];
dr["Id"] = Id;
dt.Rows.Add(dr);
}
}
}
Thanks for advice.
The error isn't coming from the DataTable because this works:
using (DataTable dt = new DataTable())
{
dt.Columns.Add("EntryDE", typeof(string));
dt.Columns.Add("Descr", typeof(string));
dt.Columns.Add("Id", typeof(int));
for (int i = 0; i < 10; i++)
{
DataRow dr = dt.NewRow();
dr["EntryDE"] = "abc";
dr["Descr"] = "xyz";
dr["Id"] = 1;
dt.Rows.Add(dr);
}
}
You've got some other problem.
You probably do want a primary key, as without it you'll be unable to update or delete rows later on.
If the ID field is going to contain duplicates, then you should add another column, call it primary_key or whatever you like, and use that column as PK.
I am developing a website in which I need to bind a grid several times {inside a for loop}
and as expected the grid overwrites the previous values and preview s the latest iteration result
You may need the code for help.Here it is:-
for (Int32 i = 0; i < k.Length; i++)
{
business.clsplugins obj = new business.clsplugins();
List<business.clspluginsprp> objprp = new List<business.clspluginsprp>();
Int32 z = Convert.ToInt32(k.GetValue(i));
objprp = obj.fnd_plugins(z);
GridView2.DataSource = objprp;
GridView2.DataBind();
}
You need to move your List declaration and GridView assignments to outside the for loop - right now you are creating a new List every iteration, you only want to create one, and then bind that to the Grid.. eg:
List<business.clspluginsprp> objprp = new List<business.clspluginsprp>();
business.clsplugins obj = new business.clsplugins();
for (Int32 i = 0; i < k.Length; i++)
{
Int32 z = Convert.ToInt32(k.GetValue(i));
objprp.Add(obj.fnd_plugins(z));
}
GridView2.DataSource = objprp;
GridView2.DataBind();
Cou cannot bind twice. Then you call DataBind(). The Control rebuild it contents based on the current data source. Old contents are discarded. So you should use a List containg ALL your data, assign it to DataSource and then call DataBind()
Try this one.
This approach may be helpful for you.Get the concept from the code and implement in your way.
ASPX:
<asp:PlaceHolder ID="plcSample" runat="server">
</asp:PlaceHolder>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
DataSet dsSample = GetDataSet();
GridView gvSample;
if (dsSample.Tables.Count > 0 && dsSample.Tables[0].Rows.Count > 0)
{
for (int iCount = 0; iCount < dsSample.Tables.Count; iCount++)
{
gvSample = new GridView();
gvSample.DataSource = dsSample.Tables[iCount];
gvSample.DataBind();
plcSample.Controls.Add(gvSample);
}
}
}
private DataSet GetDataSet()
{
DataSet ds = new DataSet();
DataTable dt;
dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("Code", typeof(string)));
DataRow dr;
dr = dt.NewRow();
dr["ID"] = 1;
dr["Code"] = "KK";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["Code"] = "Karan";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
dt = new DataTable();
dt.Columns.Add(new DataColumn("ID", typeof(string)));
dt.Columns.Add(new DataColumn("Code", typeof(string)));
dr = dt.NewRow();
dr["ID"] = 1;
dr["Code"] = "AA";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ID"] = 2;
dr["Code"] = "Arun";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
return ds;
}