Change the Column Name in Datatable in C# - c#

I trying to change the column name of the DataTable but some how I lost the data.
foreach (DataRow dr in item)
Ds.Tables[0].ImportRow(dr);
Table.Columns[0].ColumnName = "Barcode";
Table.Columns[1].ColumnName = "Description";
Table.Columns[2].ColumnName = "Price";
Table.Columns[3].ColumnName = "Cost";
Table.Columns[4].ColumnName = "Stock";
Table.Columns[5].ColumnName = "Dept #";
updateDgv.DataSource = Table;

First, the correct code is:
DataTable table = new DataTable();
table.Columns.Add("ItemNo", typeof(string));
table.Columns[0].ColumnName = "Item #";
After your code runs, you have a DataTable with one column named Item #.
There are no rows or data because you didn't add any data. So you didn't lose anything.

I have tested your code and it seems to work fine:
DataTable table = new DataTable();
table.Columns.Add("ItemNo", typeof(string));
table.Columns.Add("ItemName", typeof(string));
DataRow dr = table.NewRow();
dr[0] = "1";
dr[1] = "Name1";
table.Rows.Add(dr);
dr = table.NewRow();
dr[0] = "1";
dr[1] = "Name1";
table.Rows.Add(dr);
table.Columns[0].ColumnName = "Item #";
Probably you are trying to access data through column name later in the code and that is where it is failing. You will not loose the data by just renaming the column name. (Also its a not a good practice use special characters in table column names)
Check out the following screen shots from data visualizer
Before Column Rename:
After Column Rename:

Related

Cannot find column '0' C#

I have the following piece of code.
dt3 = new System.Data.DataTable();
foreach (DataRow sourceRow in dt2.Rows) {
DataRow destRow = dt3.NewRow();
destRow[0] = sourceRow[2];
dt3.Rows.Add(destRow);
}
And it is generating following error on line destRow[0] = sourceRow[2];
System.IndexOutOfRangeException: Cannot find column 0.
What am I doing wrong? Is there any way around it without declaring columns beforehand?
Here we create a "source" DataTable with 3 columns, and select two of those columns for the new DataTable:
DataTable srcDataTable = new DataTable();
srcDataTable.Columns.Add("Column A", typeof(string));
srcDataTable.Columns.Add("Column B", typeof(int));
srcDataTable.Columns.Add("Column C", typeof(int));
DataTable dstDataTable = new DataTable();
var desiredColumns = new[] { "Column A", "Column C" };
foreach (DataColumn col in srcDataTable.Columns)
{
if (desiredColumns.Contains(col.ColumnName))
{
dstDataTable.Columns.Add(col.ColumnName, col.DataType, col.Expression);
}
}
Now you can simply loop through the source table and copy the row data as you need it. Example for copying the rows:
foreach (DataRow srcRow in srcDataTable.Rows)
{
var newRow = dstDataTable.NewRow();
foreach (var columnName in desiredColumns)
{
newRow[columnName] = srcRow[columnName];
}
dstDataTable.Rows.Add(newRow);
}
Alternative approach using column numbers:
DataTable srcDataTable = new DataTable();
srcDataTable.Columns.Add("Column A", typeof(string));
srcDataTable.Columns.Add("Column B", typeof(int));
srcDataTable.Columns.Add("Column C", typeof(int));
DataTable dstDataTable = new DataTable();
var desiredColumns = new int[] { 0, 2 };
Dictionary<int, int> columnMap = new Dictionary<int, int>();
for (int colNum = 0; colNum < desiredColumns.Length; ++colNum)
{
columnMap[colNum] = desiredColumns[colNum];
dstDataTable.Columns.Add(srcDataTable.Columns[desiredColumns[colNum]].ColumnName, srcDataTable.Columns[desiredColumns[colNum]].DataType, srcDataTable.Columns[desiredColumns[colNum]].Expression);
}
foreach (DataRow srcRow in srcDataTable.Rows)
{
var newRow = dstDataTable.NewRow();
for (int colNum = 0; colNum < desiredColumns.Length; ++colNum)
{
newRow[colNum] = srcRow[columnMap[colNum]];
}
dstDataTable.Rows.Add(newRow);
}
This line dt3 = new System.Data.DataTable(); creates a new DataTable. But this table doesn't contain any columns yet. In fact, it's an empty table.
This line destRow[0] = sourceRow[2]; tries to set the value of the first column of your table. However, your table doesn't contain any columns yet. And this is what the error message is trying to tell you.
You have to create your column after creating the table. You can do it like this:
DataColumn idColumn = new DataColumn();
idColumn.DataType = System.Type.GetType("System.Int32");
idColumn.ColumnName = "id";
dt3.Columns.Add(idColumn);
Only after this, you will be able to put data into your first column.
Please take a look at this example in the Microsoft docs
What am I doing wrong?
Table dt3 has no column 0, because you haven't added one
Is there any way around it without declaring columns beforehand?
Even though you don't necessarily know the column name or type of dt2's column 2 at compile time, you seem to know that you definitely want column 2 from dt2 to be column 0 of dt3, so make sure you add a column to dt3 that is the same type (and giving it the same name seems reasonable too) as column 2 of dt2:
dt3 = new System.Data.DataTable();
dt3.Columns.Add(dt2.Columns[2].ColumnName, dt2.Columns[2].DataType);
foreach (DataRow sourceRow in dt2.Rows) {
DataRow destRow = dt3.NewRow();
destRow[0] = sourceRow[2];
dt3.Rows.Add(destRow);
}
You can try to use Clone() method to copy structure/columns from source table to destination table:
var dt3 = dt2.Clone();
From the docs.

How to check if a column has no value (empty) in all rows in data table in c#

I had pushed the excel file into my data table. The columns empty in excel were left empty in data table.
I guess they are not treated as null.
Can anyone help how to check for empty rows in some column in a data table .
//successfully loaded excel into datatable
OleDbDataReader dr= oledbCommand. ExecuteReader ();
dataTable. Load (dr);
Problem- empty cells in columns remained empty in data table also.
Doubt- Are these empty values in datatable are null??
If not how to check whether dataTable.Rows [1][1] is empty or not?
Please help!
You can use linq :
bool IsColumnEmpty = dt.AsEnumerable().All(dr=>string.IsNullOrEmpty( dr["name"]+""));
Test :
DataTable dt = new DataTable("myTable");
dt.Columns.Add("id", typeof (int));
dt.Columns.Add("name", typeof (string));
DataRow row = dt.NewRow();
row["id"] = 1;
//row["name"] = "";
dt.Rows.Add(row);
row = dt.NewRow();
row["id"] = 0;
//row["name"] = "zzz";
dt.Rows.Add(row);
row = dt.NewRow();
row["id"] = 2;
//row["name"] = "222";
dt.Rows.Add(row);
dt.Dump();
bool IsColumnEmpty= dt.AsEnumerable().All(dr=>string.IsNullOrEmpty( dr["name"]+""));
Console.WriteLine (IsColumnEmpty);
Result :
Let's remove // from //row["name"] = "222";
Result :

How to add rows to GridView in asp.net c# application

I've already searched many articles on this page and couldn not find the answer that would fit me.
Ok i have two projects (one is server(host) and one is client). The first one is ASP.NET Empty Web Application and the second one is ASP.NET Web Forms site.
In my host i have code for displaying users from my Entity FrameWork database. And in my client i have a form (atleast im trying to create one) where i should be able to display data (users).
Code for displaying data works fine because i've already used it before.
But somehow i cannot create a code for Gridview, which would put data from database into my cells
Lets say ID column would display user ID...Name column would display user name...
I've already set up service reference.
This is a code i've written so far, but it's giving me a few errors.
GridView1.DataSource = null;
GridView1.Refresh();
ServiceReference1.mojWebServiceSoapClient client = new ServiceReference1.mojWebServiceSoapClient();
var userList = client.getUsers();
foreach (var user in userList)
{
DataTable dt = new DataTable();
DataColumn column = new DataColumn();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
}
DataRow row = dt.NewRow();
row[0] = user.userID.ToString();
row[1] = user.Name;
row[2] = user.lName;
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Can you guys please help me fix this? I would really appreciate any input.
Btw this code works, but it only displays 1 user, instead of all (5)
You repeat binding in a for loop and it is incorrect in your case. You should first create a DataTable and next in a for loop add users to it. So the following should satisfy your nedd:
GridView1.DataSource = null;
GridView1.Refresh();
ServiceReference1.mojWebServiceSoapClient client = new ServiceReference1.mojWebServiceSoapClient();
var userList = client.getUsers();
DataTable dt = new DataTable();
DataColumn column = new DataColumn();
dt.Columns.Add("ID", typeof(Int32));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Last Name", typeof(string));
foreach (var user in userList)
{
DataRow row = dt.NewRow();
row[0] = user.userID.ToString();
row[1] = user.Name;
row[2] = user.lName;
dt.Rows.Add(row);
}
GridView1.DataSource = dt;
GridView1.DataBind();
Hope that helped

Datarow and DataCell error

I am trying to add my webpage data to DataGridView in C#.
I have successfully stored the webpage data (Source data) to a string called StrResults. Using Regex I have removed all tags. Now I need to move the content to DataGridView. Here i am getting error for DataRow and DataCell.
Here is my Code :
DataRow dr= new DataRow(); //Getting Error Here "Error 1 'System.Data.DataRow.DataRow(System.Data.DataRowBuilder)' is inaccessible due to its protection level"
foreach (Match m in m1)
{
String value=m.Value;
String[] data=value.split(':');
DataCell dc=new DataCell(); //Getting Error Here, "Error 2 The type or namespace name 'DataCell' could not be found (are you missing a using directive or an assembly reference?)"
dc.value=data[1];
dr.cell.add(dc);
}
dataGridView1.rows.add(dr);
I have added my current code below as suggested. Only one error is showing for DataCells
DataTable dt = new DataTable();
DataRow dr = dt.NewRow();
foreach (Match m in m1)
{
String value = m.Value;
String[] data = value.Split(':');
DataCell dc = new DataCell(); //Getting Error Here
dc.value = data[1];
dr.Cell.add(dc);
}
dataGridView1.Rows.Add(dr);
use this instead of DataRow dr= new DataRow()
DataTable dtTable = New DataTable();
DataRow r = dTable.NewRow()
You can't create a DataRow that way. You should use DataTable.NewRow()
DataRow row = dt.NewRow();
And there is no type named DataCell in System.Data. In fact, you can't add cells to your rows. You should add them to your DataTable as DataColumns:
DataTable table = new DataTable();
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "name";
table.Columns.Add(column);
foreach (Match m in m1)
{
DataRow row = table.NewRow();
String value=m.Value;
String[] data=value.split(':');
row["id"] = data[0]; // For example
row["name"] = data[1];
table.Rows.Add(row);
}
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = table;

Table doesn't have a primary key when adding a new row to datatable

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.

Categories

Resources