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
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 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;
I want to Delete the Multiple records from the DataTable
For example :
in my case PaperId is Repeating several Times.I want to Delete it all Duplicate records.
i have written code but loop is giving error
DataSet ds = new DataSet();
sqlDad.Fill(ds);
DataTable dt1 = new DataTable();
ds.Tables.Add(dt1);
dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1;
List<DataRow> rowsToDelete = new List<DataRow>();
foreach(DataRow dr in ds.Tables[0].Rows)
{
int r = ds.Tables[0].Columns.Count;
string x = dr.ItemArray[0].ToString();
int counter = 0;
foreach (DataRow dr1 in ds.Tables[0].Rows)
{
if (x == dr1.ItemArray[0].ToString())
{
counter++;
}
if (counter > 1)
{
rowsToDelete.Add(dr1);
foreach (DataRow row in rowsToDelete)
{
dt2.Rows.Remove(row);
}
dt2.AcceptChanges();
rowsToDelete.Clear();
}
}
Using the DefaultView of the DataTable and setting the sort order on the column that you don't want repeats to appear. You could loop over the rows and delete all the rows after the first one
// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1)
return;
// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;
// Set an initial value ( I choose an empty string but you could set to something not possible here
string x = string.Empty;
// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
// If we have a new value, keep it else delete the row
if(x != dr[0].ToString())
x = dr[0].ToString();
else
dr.Row.Delete();
}
// Finale step, remove the deleted rows
dt1.AcceptChanges();
Try This
DataRow[] rows;
rows=dataTable.Select("UserName = 'ABC'"); // UserName is Column Name
foreach(DataRow r in rows)
r.Delete();
If you want to remove the entire row from DataTable ,
try this
DataTable dt = new DataTable(); //User DataTable
DataRow[] rows;
rows = dt.Select("UserName = 'KarthiK'");
foreach (DataRow row in rows)
dt.Rows.Remove(row);
I have a datatable with 20 columns. But i don't need all the columns for the current processing except 5. So i did the below to remove the columns
List<string> clmnames = new List<string>() { "clm6","clm7"..."clm20" };
foreach (string dcName in clmnames)
{
TestAndRemoveColumn(dcName, ds.Tables["TestTable"]);
}
private void TestAndRemoveColumn(string dcName,DataTable datatable)
{
DataColumnCollection dcCollection = datatable.Columns;
if (dcCollection.Contains(dcName))
{
dcCollection.Remove(dcName);
}
}
Instead of looping through the 15 times is there any other way to achieve using easily ?
try this
List<string> listtoRemove = new List<string> { "CLM6", "CLM7", "CLM20" };
for (int i = dt.Columns.Count - 1; i >= 0; i--)
{
DataColumn dc = dt.Columns[i];
if (listtoRemove.Contains(dc.ColumnName.ToUpper()))
{
dt.Columns.Remove(dc);
}
}
In some scenarios may be preferable to clone DataTable and specify columns to copy.
DataView view = new DataView(table);
DataTable table2 = view.ToTable(false, "clm6", "clm7", ...);
Problem seems to be in your code, you get all the comlumns from the datatable then remove the columns but you have not again assign the columns to that datatable
first you get columns
DataColumnCollection dcCollection = datatable.Columns; // get cols
if (dcCollection.Contains(dcName))
{
dcCollection.Remove(dcName); /// remove columns
// but you have not updated you datatable columns.
here should be something like this
datatable.Columns = dcCollection; /// i don't know this will work or not check it
}
Try this
DataTable dt;
dt.Columns.Remove("columnName");
dt.Columns.RemoveAt(columnIndex);
you can use them as
private void TestAndRemoveColumn(string dcName,DataTable datatable)
{
DataTable dt = datatable;
dt.Columns.Remove("dcName");
}
Alternatively you can select only the required columns(Only 5 in your case) like this.
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Value");
dt.Rows.Add("1", "One");
dt.Rows.Add("2", "Two");
string[] arr= new string[1];
arr[0] = "Value";//add the required columns to the array
//return only the required columns.
DataTable dt2 = dt.DefaultView.ToTable(false, arr);
You could join the columns you want remove with the available columns:
var keepColNames = new List<String>(){ "clm5" };
var allColumns = tbl.Columns.Cast<DataColumn>();
var allColNames = allColumns.Select(c => c.ColumnName);
var removeColNames = allColNames.Except(keepColNames);
var colsToRemove = from r in removeColNames
join c in allColumns on r equals c.ColumnName
select c;
while (colsToRemove.Any())
tbl.Columns.Remove(colsToRemove.First());
If you know that you only have few remaining columns, you could add the column(s):
var colsToAdd = (from keepCol in keepColNames
join col in tbl.Columns.Cast<DataColumn>()
on keepCol equals col.ColumnName
select col).ToList();
tbl.Columns.Clear();
foreach (var colToAdd in colsToAdd)
tbl.Columns.Add(colToAdd);
i get the following exception (missing primary key) in the line of using Find() method
"Table doesn't have a primary key."
I've rechecked the Database and all Primary Key columns are set correctly.
my code:
DataTable dt = p.GetAllPhotos(int.Parse(Id));
DataTable temp = new DataTable();
temp = dt.Clone();
temp = (DataTable)(Session["currentImage"]);
DataTable dtvalid = new DataTable();
dtvalid = dt.Clone();
DataRow[] drr = new DataRow[1];
drr[0] = dt.Rows.Find((int.Parse(temp.Rows[0]["photoId"].ToString()))+1);
foreach (DataRow dr in drr)
{
dtvalid.ImportRow(dr);
}
dtvalid.AcceptChanges();'
You need to set the PrimaryKey property of your DataTable object before you call Find
DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = dt.Columns["<columnname>"];
dt.PrimaryKey = keyColumns;