How to add new DataRow into DataTable? - c#

I have a DataGridView binded to a DataTable (DataTable binded to database). I need to add a DataRow to the DataTable. I'm trying to use the following code:
dataGridViewPersons.BindingContext[table].EndCurrentEdit();
DataRow row = table.NewRow();
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}
But it doesn't work, DataGridView has never been added a new row. Please, tell me, how can I fix my code?
Thank you in advance.

You can try with this code - based on Rows.Add method
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
Reference: https://learn.microsoft.com/dotnet/api/system.data.datarowcollection.add?view=net-5.0#System_Data_DataRowCollection_Add_System_Data_DataRow_

I found dotnetperls examples on DataRow very helpful. Code snippet for new DataTable from there:
static DataTable GetTable()
{
// Here we create a DataTable with four columns.
DataTable table = new DataTable();
table.Columns.Add("Weight", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Breed", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
return table;
}

//َCreating a new row with the structure of the table:
DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);
//Giving values to the columns of the row(this row is supposed to have 28 columns):
for (int i = 0; i < 28; i++)
{
row[i] = i.ToString();
}

You have to add the row explicitly to the table
table.Rows.Add(row);

If need to copy from another table then need to copy structure first:
DataTable copyDt = existentDt.Clone();
copyDt.ImportRow(existentDt.Rows[0]);

This works for me:
var table = new DataTable();
table.Rows.Add();

try table.Rows.add(row); after your for statement.

GRV.DataSource = Class1.DataTable;
GRV.DataBind();
Class1.GRV.Rows[e.RowIndex].Delete();
GRV.DataSource = Class1.DataTable;
GRV.DataBind();

Related

How to bind data to the columns in C# Windows Forms grid view, which are stored in rows in SQL table

Please refer the images. How to bind the SQL table data which are stored in rows in to data grid view (C# Windows Forms) as columns. Also I have created column[0] as a hard coded column. I need to bind these data which is coming from SQL to column1. Please help me. Thanks in advance . :-)
You can create a method which rotate the DataTable and swap columns and rows this way:
public DataTable Rotate(DataTable table)
{
var output = new DataTable();
int i = 1;
output.Columns.Add(" ");
foreach (DataRow r in table.Rows)
output.Columns.Add((i++).ToString());
foreach (DataColumn c in table.Columns)
{
var list = new List<object>();
list.Add(c.ColumnName);
var x = table.AsEnumerable().Select(r => string.Format("{0}", r[c])).ToArray();
list.AddRange(x);
output.Rows.Add(list.ToArray());
}
return output;
}
Then you can use it to rotate the original table:
to rotated table:
or even with some simple tricks like this:
Here is the code which I used to create the example:
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Date", typeof(DateTime));
dt.Rows.Add(100, "A", DateTime.Now);
dt.Rows.Add(200, "B", DateTime.Now.AddDays(1));
dt.Rows.Add(300, "C", DateTime.Now.AddDays(2));
dt.Rows.Add(400, "D", DateTime.Now.AddDays(3));
this.dataGridView1.DataSource = dt;
this.dataGridView2.DataSource = Rotate(dt);
//To hide column headers and show Id,Name,Date on rows headers, un-comment following codes:
//dataGridView2.ColumnHeadersVisible = false;
//dataGridView2.Columns[0].Visible = false;
//for (int i = 0; i < dataGridView2.Rows.Count; i++)
// dataGridView2.Rows[i].HeaderCell.Value = dataGridView2.Rows[i].Cells[0].Value;

Add column to DataTable and move columns to right

I have a DataTable with 2 columns in it. I would like to insert another column to the start, and move those 2 columns to the right by 1.
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
Any ideas how I could do this?
Thanks.
Try this.
DataColumn column = dtCurrentTable.Columns.Add("Column Name", typeof(<<The data type of your column>>));
column.SetOrdinal(0);// to put the column in position 0;
Do Something like this>>
DataTable workTable = new DataTable("Customers");
DataColumn workCol = workTable.Columns.Add("CustID", typeof(Int32));
workCol.AllowDBNull = false;
workCol.Unique = true;
workTable.Columns.Add("CustLName", typeof(String));
workTable.Columns.Add("CustFName", typeof(String));
workTable.Columns.Add("Purchases", typeof(Double));
Hope its helpfull.

Can't bind DataTable to GridView

Hey guys I've just started programming and I'm running into a problem. The new Datatable i created doesnt show in GridView2 when button1 is clicked. Although it is filled with data from the "planning" table(checked that dtPlanning is filled with the TextBoxes in comment).
So in short: I want to get DataTable planning into the new DataTable dtPlanning and display it in a gridview.
Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dtPlanning = new DataTable();
dtPlanning.Columns.Add("Courseday", typeof(int));
dtPlanning.Columns.Add("Part", typeof(string));
dtPlanning.Columns.Add("Design", typeof(string));
dtPlanning.Columns.Add("Lesson", typeof(string));
//DataRow dr = planning.Rows[1];
//TextBox2.Text = (dr["Daynumber"]).ToString();
//TextBox3.Text = (dr["Part"]).ToString();
//TextBox4.Text = (dr["Design"]).ToString();
//TextBox5.Text = (dr["Lesson"]).ToString();
for (int i = 0; i < dtPlanning.Rows.Count; i++)
{
DataRow dr = dtPlanning.NewRow();
foreach (DataRow datarow in planning.Rows)
{
dtPlanning.Rows.Add(datarow);
}
}
GridView2.DataSource = dtPlanning;
GridView2.DataBind();
}
Source code:
<asp:GridView ID="GridView2" runat="server">
Thank you for your help.
Logically, dtPlanning.Rows.Count = 0 because this table is just initialized!
Secondly, you cannot Add a row from one table to another, user Import
for (int i = 0; i < planning.Rows.Count; i++)
{
dtPlanning.ImportRow(planning.Rows[i]);
}
I wonder why don't you just use the table planning?
You must:
Add to DataSet a new DataTable
Add to DataTable a new Columns
And GridView2.DataSource=YourNameDataSet.Tables[index_of_DataTable_in_DataSet].DefaultView;

Best way add a new column with sequential numbering in an existing data table

I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.
I tried the following code. But did not work.
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);
Will setting any expression help in this scenario ?
Thanks in Advance
I think you could achieve that by using a 2nd "helper" data table that would contain just an auto-increment field and then you populate/merge it with the existing data, something like this:
DataTable dtIncremented = new DataTable(dt.TableName);
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dtIncremented.Columns.Add(dc);
dtIncremented.BeginLoadData();
DataTableReader dtReader = new DataTableReader(dt);
dtIncremented.Load(dtReader);
dtIncremented.EndLoadData();
And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.
below code worked for me
Code is Edited
// Added temp rows so that this solution can mimic actual requirement
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("Col");
dt.Columns.Add(dc1);
for(int i=0;i<10;i++)
{
DataRow dr = dt.NewRow();
dr["Col"] = i.ToString();
dt.Rows.Add(dr);
}
// Added new column with Autoincrement,
DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.DataType = typeof(Int32);
// Handeled CollectionChanged event
dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged);
dt.Columns.Add(dc);
// After column added demostratation
DataRow dr1 = dt.NewRow();
dt.Rows.Add(dr1);
void Columns_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
DataColumn dc = (e.Element as DataColumn);
if (dc != null && dc.AutoIncrement)
{
long i = dc.AutoIncrementSeed;
foreach (DataRow drow in dc.Table.Rows)
{
drow[dc] = i;
i++;
}
}
}
You'll have to build a whole new datatable for this and manually deep-copy each row one by one from the old table to the new. Sorry.

How to add identity column to datatable using c#

How to add identity column to datatable using c#. Im using Sql compact server.
You could try something like this maybe?
private void AddAutoIncrementColumn()
{
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = true;
column.AutoIncrementSeed = 1000;
column.AutoIncrementStep = 10;
// Add the column to a new DataTable.
DataTable table = new DataTable("table");
table.Columns.Add(column);
}
DataTable table = new DataTable("table");
DataColumn dc= table.Columns.Add("id", typeof(int));
dc.AutoIncrement=true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
// Add the new column name in DataTable
table.Columns.Add("name",typeof(string));
table.Rows.Add(null, "A");
table.Rows.Add(null, "B");
table.Rows.Add(null, "C");
If the DataTable is already populated. you can use below method
void AddAndPopulateDataTableRowID(DataTable dt, string col, bool isGUID)
{
if(isGUID)
dt.Columns.Add(col, typeof(System.Guid));
else
dt.Columns.Add(col, typeof(System.Int32));
int rowid = 1;
foreach (DataRow dr in dt.Rows)
{
if (isGUID)
dr[col] = Guid.NewGuid();
else
dr[col] = rowid++;
}
}
You don't do autoincrement on DataTable (or front-end for that matter), unless you want to make your application a single user application only.
If you need the autoincrement, just do it in database, then retrieve the autoincremented id produced from database to your front-end.
See my answer here, just change the SqliteDataAdapter to SqlDataAdapter, SqliteConnection to SqlConnection, etc : anyway see why I get this "Concurrency Violation" in these few lines of code??? Concurrency violation: the UpdateCommand affected 0 of the expected 1 records
Just my two cents. Auto-increment is useful in a Winform app (stand alone as Michael Buen rightly said), i.e.:
DatagridView is being used to display data that does not have a "key field", the same can be used for enumeration.
I dont think its a good idea to use autoincrement on datatable if you are using insert and delete to a datatable because the number will not be rearranget, no final i will share a small idea how can we use autoincrement manual.
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(int));
dt.Columns.Add("Produto Nome", typeof(string));
dt.Rows.Add(null, "A");
dt.Rows.Add(null, "B");
dt.Rows.Add(null, "C");
for(int i=0;i < dt.Rows.Count;i++)
{
dt.Rows[i]["ID"] = i + 1;
}
always when finalizing the insert or delete must run this loop
for(int i=0;i < dt.Rows.Count;i++)
{
dt.Rows[i]["ID"] = i + 1;
}

Categories