DataTable row filling in C# - c#

I am trying to add row in DataTable CartDT using row[], which is a string array.
DataTable CartDT = new DataTable();
public void DataTableColumn()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
string[] row = new string[5];
row[0] = arg[0]; //Product_Name
row[1] = arg[1]; //Product_ID
row[2] = itemQuantity.Text; //OrderQTY
row[3] = arg[2]; //Price
row[4]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Now when I execute it, it gives the error that "Input array is longer than the number of columns in this table"
The array row[] has exactly 5 elements in it & also DataTable CartDT has also 5 columns.
Now i am not able to find exactly where i am wrong.
Please help me to find the bug.
Thanx in advance.

Instead do this
DataRow dr = CartDT.NewRow();
Then
dr[0] = arg[0];
and so on. In the end
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
This way the instance of Row will have CartDT schema.
DataTable CartDT = new DataTable();
public void CreateDataTableColumns()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
if (CartDT.Columns.Count = 0)
{
CreateDataTableColumns();
}
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity =
(TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow dr = CartDT.NewRow();
dr[0] = arg[0]; //Product_Name
dr[1] = arg[1]; //Product_ID
dr[2] = itemQuantity.Text; //OrderQTY
dr[3] = arg[2]; //Price
dr[4] = (Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString(); // calculate total price
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}

Debug, and break on
CartDT.Rows.Add(row);
and see how many columns are in CartDT; I think you don't call DataTableColumn() at the right time.
Your code having to do with row insertion works just fine
DataTable CartDT = new DataTable();
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
string[] row = new string[5];
row[0] = "1"; //Product_Name
row[1] = "2"; //Product_ID
row[2] = "3"; //OrderQTY
row[3] = "4"; //Price
row[4] = "5";// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
for (int i = 0; i < 5; i++)
{
Console.WriteLine(CartDT.Rows[0][i]);
}
Console.Read();

Try Below Code:
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow row = CartDT.NewRow();
row["Product_Name"] = arg[0]; //Product_Name
row["Product_ID"] = arg[1]; //Product_ID
row["OrderQTY"] = itemQuantity.Text; //OrderQTY
row["Price"] = arg[2]; //Price
row["TotalPrice"]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();
CartDt.Rows.Add(row);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}

Related

GridView text field data posting issue

I am Not getting text field values into grid view. Only row increases but I do not get the text.
This is the code that I have for the purpose.
DataTable dt1 = new DataTable();
bool flag = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gridVIEWData();
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
}
protected void gobtn_Click(object sender, EventArgs e)
{
if (Session["dtInSession"] != null)
dt1 = (DataTable)Session["dtInSession"];
DataRow dr = dt1.NewRow();
dr["Product"] = DropDownList1.SelectedItem;
dr["Size"] = DropDownList2.SelectedItem;
dr["Case"] = casetxt.Text;
dr["Weight"] = TextBox1.Text;
dr["Price"] = TextBox2.Text;
dt1.Rows.Add(dr);
Session["dtInSession"] = dt1;
Gridview1.DataSource = dt1;
Gridview1.DataBind();
}
private void gridVIEWData()
{
dt1.Columns.Add("Product", typeof(string));
dt1.Columns.Add("Size", typeof(string));
dt1.Columns.Add("Case", typeof(string));
dt1.Columns.Add("Weight", typeof(string));
dt1.Columns.Add("Price", typeof(string));
Session["dtInSession"] = dt1;
}
Please Can any one help me
**I hope you looking for something like this**
protected void BindGridview1()
{
DataTable dtt = new DataTable();
DataTable dt = (DataTable)Session["od"];
dtt.Columns.Add("BookingNO", typeof(string));
dtt.Columns.Add("ItemName", typeof(string));
dtt.Columns.Add("Size", typeof(string));
dtt.Columns.Add("Unit", typeof(string));
dtt.Columns.Add("Price", typeof(string));
dtt.Columns.Add("PendingQty", typeof(string));
for (int i = 0; i < dtt.Rows.Count; i++)
{
DataRow dr = dtt.NewRow();
dr["BookingNO"] = string.Empty;
dr["ItemName"] = string.Empty;
dr["Size"] = string.Empty;
dr["Unit"] = string.Empty;
dr["Price"] = string.Empty;
dr["PendingQty"] = string.Empty;
dtt.Rows.Add(dr);
}
dtt = dt;
gvDetails.DataSource = dtt;
gvDetails.DataBind();
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
TextBox BookingNO = (TextBox)gvDetails.Rows[i].FindControl("BookingNO");
TextBox ItemName = (TextBox)gvDetails.Rows[i].FindControl("ItemName");
TextBox Size = (TextBox)gvDetails.Rows[i].FindControl("Size");
TextBox Unit = (TextBox)gvDetails.Rows[i].FindControl("Unit");
TextBox Price = (TextBox)gvDetails.Rows[i].FindControl("Price");
//TextBox DueDate = (TextBox)gvDetails.Rows[i].FindControl("DueDate");
TextBox PendingQty = (TextBox)gvDetails.Rows[i].FindControl("PendingQty");
BookingNO.Text = Session["BookingNO1"].ToString();
ItemName.Text = dt.Rows[i]["ItemName"].ToString();
Size.Text = dt.Rows[i]["Size"].ToString();
Unit.Text = dt.Rows[i]["Unit"].ToString();
Price.Text = dt.Rows[i]["Price"].ToString();
//DueDate.Text = dt.Rows[i]["DueDate"].ToString();
PendingQty.Text = dt.Rows[i]["PendingQty"].ToString();
}
}

How to display row number in gridview

I use code below but it didint work.. It didnt show me column with that field.
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
I add my other columns in code behind and meaby it's the problem?
OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);
DataTable dt = new DataTable();
connProdcc1.Open();
sqlArchiveData.Fill(dt);
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName.Replace("_"," ");
field.SortExpression = column.ColumnName;
AggregateGridView.Columns.Add(field);
}
AggregateGridView.DataSource = dt;
AggregateGridView.DataBind();
Does anone have any idea how to do this in other way?
I try to this like below but it's counts my row number after all data I Fill() into a DataTable and then add to each row a number
DataColumn columnIndexRow = new DataColumn();
columnIndexRow.DataType = System.Type.GetType("System.Int32");
columnIndexRow.ColumnName = "id";
dt.Columns.Add(columnIndexRow);
for (int i = 0; i < dt.Rows.Count; i++)
{
// your index is in i
var row = dt.NewRow();
row["id"] = i;
dt.Rows.Add(row);
}
ADD row number field to DataTable
OleDbDataAdapter sqlArchiveData = new OleDbDataAdapter(sql_archive);
DataTable dt = new DataTable();
connProdcc1.Open();
sqlArchiveData.Fill(dt);
dt = AutoNumberedTable(dt);
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName.Replace("_"," ");
field.SortExpression = column.ColumnName;
AggregateGridView.Columns.Add(field);
}
AggregateGridView.DataSource = dt;
AggregateGridView.DataBind();
private DataTable AutoNumberedTable(DataTable SourceTable)
{
DataTable ResultTable = new DataTable();
DataColumn AutoNumberColumn = new DataColumn();
AutoNumberColumn.ColumnName="S.No.";
AutoNumberColumn.DataType = typeof(int);
AutoNumberColumn.AutoIncrement = true;
AutoNumberColumn.AutoIncrementSeed = 1;
AutoNumberColumn.AutoIncrementStep = 1;
ResultTable.Columns.Add(AutoNumberColumn);
ResultTable.Merge(SourceTable);
return ResultTable;
}
Hope this might help. :)
Note: I haven't tested this code.
Thanks guys! I just find out the answer. I do something like updating a cell at row index and first column
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i][0] = i;
}

Append rows to datatable in foreach c#

I need to append rows one by one. The below code only adds the current rows and how can I add rows on top of the existing ones?
DataTable dt = new .DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
DataRow row = dt.NewRow();
foreach (Object form in Obj)
{
string str1 = "hi";
string str2 = "hey";
row["Name"] = str1;
row["Property"] = str2;
dt.Rows.Add(row);
}
Really appreciate any suggestions?
Update 1:
My actual code
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
if (crobj.SourceName.StartsWith("{#"))
{
foreach (CRObject crform in lstObj)
{
if (crform.FormulaForm == crobj.SourceName)
{
System.Data.DataRow newRow = dt.NewRow();
newRow["Name"] = "hi";
newRow["Property"] = "hey";
dt.Rows.Add(newRow);
}
}
}
You only have one row (DataRow) object which you keep re-editing. Declare a new one within the scope of the loop:
foreach (Object form in Obj)
{
DataRow row = dt.NewRow();
//...
dt.Rows.Add(row);
}
Small change:
DataTable dt = new .DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
foreach (Object form in Obj)
{
DataRow row = dt.NewRow(); <<<------------
string str1 = "hi";
string str2 = "hey";
row["Name"] = str1;
row["Property"] = str2;
dt.Rows.Add(row);
}
By generating a new row inside the loop, it is treated as a new row instead of the same one.
EDIT: if this doesn't work, then the Obj collection is probably not containing values. Try this to test:
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
for (int i=0; i<5; i++)
{
DataRow row = dt.NewRow();
string str1 = "hi";
string str2 = "hey";
row["Name"] = str1;
row["Property"] = str2;
dt.Rows.Add(row);
}
With this, the resulting data table contains 5 rows.

Winform C# Update DataGridView on DataTable Cell value changed

I have DataGridView and DataTable, DataTable is assigned as a datasource in DataGridView.
When I change some value in DataTable it is not update on the view.
So How can i achive this
I have tried following things
BindingSource
Refresh()
Demo Code
DataGridView datagrid = new DataGridView();
DataTable dt = new DataTable();
dt.Columns.Add("No");
dt.Columns.Add("Name");
for (int i = 1; i <= 10; i++)
{
DataRow row = dt.NewRow();
row[0] = i;
row[1] = "ABC";
dt.Rows.Add(row);
}
datagrid.DataSource = dt;
Here my above code
When i change some value in DataTable it is not reflect in DataGridView
dt.Rows[0][1] = "XYZ";
So Please help me....
I am able to do this, which works:
private DataTable _dt = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
_dt.Columns.Add("LongText");
DataRow dr = _dt.NewRow();
dr[0] = "One";
_dt.Rows.Add(dr);
dr = _dt.NewRow();
dr[0] = "Two";
_dt.Rows.Add(dr);
dr = _dt.NewRow();
dr[0] = "Three";
_dt.Rows.Add(dr);
dataGridView1.DataSource = _dt;
}
private void button1_Click(object sender, EventArgs e)
{
_dt.Rows[0][0] = "daddy";
}
You need to add your datagrid to your form, like this:
private void Form1_Load(object sender, EventArgs e)
{
DataGridView datagrid = new DataGridView();
DataTable dt = new DataTable();
//add this line
Controls.Add(datagrid);
dt.Columns.Add("No");
dt.Columns.Add("Name");
for (int i = 1; i <= 10; i++)
{
DataRow row = dt.NewRow();
row[0] = i;
row[1] = "ABC";
dt.Rows.Add(row);
}
datagrid.DataSource = dt;
dt.Rows[0][1] = "XYZ";
}
Result:

from datatable to array، no loop

Following Code for transmission to the list box is :
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("BestSite", typeof(string));
dt.Columns.Add(dc);
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i.ToString() + " = stackoverflow";
dt.Rows.Add(dr);
}//EndFor
var Query = from mycolumn in dt.AsEnumerable()
where mycolumn.Field<string>("BestSite") != string.Empty
select mycolumn;
listBox1.DataSource = Query.AsDataView();
listBox1.DisplayMember = "BestSite";
Transfer to array what should be? no loop
string[] myvalue = new string[Query.AsDataView().Count];
Finally realized
Correct answer :
private string ConvertToString(DataRow dr)
{
return Convert.ToString(dr[0]);
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("BestSite", typeof(string));
dt.Columns.Add(dc);
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i.ToString() + " = stackoverflow";
dt.Rows.Add(dr);
}//EndFor
//var Query = from mycolumn in dt.AsEnumerable()
// where mycolumn.Field<string>("BestSite") != string.Empty
// select mycolumn;
DataRow[] myrow = new DataRow[dt.Rows.Count];
dt.Rows.CopyTo(myrow, 0);
string[] myString = Array.ConvertAll(myrow, new Converter<DataRow, string>(ConvertToString));
foreach (string a in myString)
{
listBox1.Items.Add(a);
}
}
If I understood your question correctly...
string[] myvalue = Query.Select(i => i.Field<string>("BestSite")).ToArray();
This example assumes:
=> datatable is non zero length
=> values are "parsable" to double.
coln = "PurchasePrice";
double[] arr_val = Array.ConvertAll<DataRow, double>
(
dattbl.Select(),
delegate (DataRow rw) { return
double.Parse(rw[coln].ToString()); }
);
// ... and for example
double total = arr_val.Sum();

Categories