Datarow and DataCell error - c#

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;

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 add column dynamically in datatable in c#

i want to create datatable in which i want to add column names dynamically, my column names are coming from database, which is not fixed column name every time different its depend on user selection
i using sql server and c#.
Following code add column and row dynamically in the datatable:
DataTable dt = new DataTable();
var properties = typeof(model).GetProperties();
foreach (PropertyInfo p in properties)
{
dt.Columns.Add(p.Name, p.PropertyType);
}
foreach (var data in taskData)
{
var values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(data, null);
}
dt.Rows.Add(values);
}
Here is an option
var dt = new DataTable();
dt.Columns.Add("Name",typeof(string));
you may also try this one.
var dt = new DataTable();
DataColumn column = new DataColumn();
{
column.Caption = "Name";
column.ColumnName = "ColumnName";
column.DataType = typeof(String);
dt.Columns.Add(column);
}

Unable to import or add row from a datatable

I am trying to add a row acquired from a database to a DataTable.
First I tried Using bucketdt.Rows.Add(r); I got an error saying Row belongs to another Table
Then I used bucketdt.ImportRow(r); then it doesn't copy the row at all!
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
//DataTable f = new DataTable();
dosObject = new DataOperations();
bucketdt = new DataTable();
count=0;
foreach (string key in Session.Keys)
{
string val = Session[key].ToString();
DataRow r = bucketdt.NewRow();
r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0];
bucketdt.ImportRow(r);
bucketdt.AcceptChanges();
}
GridView1.Enabled = true;
GridView1.DataSource = bucketdt;
GridView1.DataBind();
}
else
Response.Redirect(FormsAuthentication.LoginUrl);
am I missing something?
Now I tried adapting the code as told by #wonko79
DataTable f = new DataTable();
dosObject = new DataOperations();
bucketdt = new DataTable();
count=0;
foreach (string key in Session.Keys)
{
string val = Session[key].ToString();
DataRow r = bucketdt.NewRow();
f = dosObject.SubCategoryDetails2(Convert.ToInt16(val));
r["Id"]=f.Rows[0].ItemArray[0].ToString();
r["SubCategoryName"] = f.Rows[0].ItemArray[1].ToString();
r["Make"] = f.Rows[0].ItemArray[2].ToString();
r["Cost"] = f.Rows[0].ItemArray[3].ToString();
//bucketdt.ImportRow(r);
bucketdt.Rows.Add(r);
bucketdt.AcceptChanges();
n now it says the row doesnt contain Column: 'Id' does not belong to table .
You are overwriting your DataRow r which follows the schema of bucketdt with a DataRow folowing another schema.
DataRow r = bucketdt.NewRow();
r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0]; // overwrites r with a DataRow following another schema

Change the Column Name in Datatable in 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:

Add rows in a gridview c#

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

Categories

Resources