From this code I am trying to only display data rows that contain the fields "DBY" in the Station_From_Code column and "MAT" in the Station_To_Column. This will then be printed onto a HTML page. These fields are definitely in the datatable but when I run this cod the table is empty. I am not used to working with data tables in C# so apologies for the poor coding.
dynamic schedluedContent = JsonConvert.DeserializeObject(scheduledJson);
JArray items2 = new JArray();
foreach (JObject stops in schedluedContent.stops)
{
DataTable dt = new DataTable();
DataRow dr;
dr = dt.NewRow();
dr["From_Station_Code"] = stops["station_code"];
dr["To_Station_Code"] = stops["station_code"];
dt.Rows.Add(dr);
DataRow[] result = dt.Select("From_Station_Code = 'DBY' AND To_Station_Code = 'MAT'");
dt.Rows.Add(result);
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
}
It's a long time I have not seen this style of code for working with database tables! EntityFramework comes to change and surely ease the way of working with database and prevent different risks of using SQL commands inside the code.
If you use EF, your code will become something like bellow:
var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;
You can use find match rows and add in new datatable, that contains only your match rows data then you can bind this dt to gridview.
DataTable dt = new Datatable(); // Lets this datatable have data;
Datatable dt2 = new Datatable(); // Copy all matching rows
foreach (DataRow dr in dt.Rows)
{
if (dr["From_Station_Code"].ToString() == "DBY" && dr["To_Station_Code"].ToString() == "MAT")
{
dt2.Rows.Add(dr);
}
}
GridViewTrainTimes.DataSource = dt;
GridViewTrainTimes.DataBind();
Related
I'm trying to retrieve the second row from a DataTable but this is not returning a value. What could be the problem as the DropDown populates just fine.
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DropDown.DataSource = dt;
DropDown.DataTextField = "FirstName";
DropDown.DataValueField = "FirstName";
DropDown.DataBind();
con.Close();
var secondRow = dt.Rows[2].ToString(); // This should return the second row in my datatable.
}
DataTable.Rows[int] will give you the DataRow object. If you do dt.Rows[2].ToString(), you are going to get the string representation of the object type.
The index starts at 0. Hence for 2nd row, you will query dt.Rows[1]. Further, You can extract the value of a column in the row and for that, you have to mention the column index or name like - dt.Rows[1][0] or dt.Rows[1]["col1"]
You can also loop through all the columns in the row like below:
foreach (DataColumn col in dt.Columns)
{
var columnValue = dt.Rows[1][col];
}
I know this is kind of a stupid question and i may sound a bit confused ('cause i really am).I'm programming a software for work but i'm new to c#.
I have a Form with a TabControl. In each TabPage i have a DataGridView.
i need to execute this code for each DataGridView
while (reader.Read())
{
DataTable dtSchema = reader.GetSchemaTable();
DataTable dt = new DataTable();
// You can also use an ArrayList instead of List<>
List<DataColumn> listCols = new List<DataColumn>();
if (dtSchema != null)
{
foreach (DataRow drow in dtSchema.Rows)
{
string columnName = System.Convert.ToString(drow["ColumnName"]);
DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));
column.Unique = (bool)drow["IsUnique"];
column.AllowDBNull = (bool)drow["AllowDBNull"];
column.AutoIncrement = (bool)drow["IsAutoIncrement"];
listCols.Add(column);
dt.Columns.Add(column);
}
}
// Read rows from DataReader and populate the DataTable
while (reader.Read())
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i < listCols.Count; i++)
{
dataRow[((DataColumn)listCols[i])] = reader[i];
}
dt.Rows.Add(dataRow);
}
dataGridView1 = dt;
}
reader.NextResult();
I don't want to copy and paste the code for each datagridview because the only words that should change in this code portion is the name of the DGV but i don't know how to automatically change the datagridview name.
Maybe some nested if to compare the name of the datagridview with a string could be a solution but i suppose that datagridview.tostring() doesn't give me the string of the control's name but the content.
i'm sorry if a question like this already existed, i wasn't able to find it.
You can use foreach to loop over the DGVs:
foreach (DataGridView dgv in new[] { dataGridView1, otherDGV })
{
// code to happen to both DGVs goes here.
}
I have one datatable which has four or five columns. I dont know exactly the columns name and its count. But I want to bind the first row of the datatable into the GridView. How to do this? I need all your suggestions please.
Linq should be helpful here to get first item.
var Temp = dt.AsEnumerable().Take(1).CopyToDataTable();
use the filter in the datatable :
dt.Select("ID = 1");
you can try like this..
dt = new DataTable();
dt_Property.Columns.Add("Field1");
int i = 0;
DataRow row = null;
foreach (DataRow r in ds.Tables[0].Rows)
{
row = dt.NewRow();
row["Field1"] = ds.Tables[0].Rows[i][1];
dt_Property.Rows.Add(row);
i = i + 1;
}
dataGridView1.DataSource = dt;
I have a datatable say dt1( which keeps changing its inside a loop). I have another datatable say dt2( initially its null). Now I have to append the Rows of dt1 in dt2. I tried using Merge(), but the previous rows of dt2 are vanishing.
Any idea How to do this ??
You are clearing the dt2 table everytime the loop runs. Try this:
DataTable dt1 = null; DataTable dt2 = null;
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
if(dt2 == null)
{
dt2 = dt1.Clone();
}
dt2.Merge(dt1,true);
}
Also, if the query restriction based on i is applied to a primary key column you can use
dt2.ImportRow(dt1.Rows[0]);
instead of
dt2.Merge(dt1,true);
Use the ImportRow method, like this:
var table2 = new DataTable();
foreach(DataRow row in table1.Rows)
table2.ImportRow(row);
Based on your code, I see that you're using dt2 = dt1.Clone();
That's wiping all the contents in dt2, so you're only adding the current contents of dt1 to dt2.
Instead of cloning you should just merge the contents of dt1 to dt2.
Another derivative to João Angelo's answer would be to initialize dt2 ahead of time and then you can remove the null check
DataTable dt1 = null; DataTable dt2 = new DataTable();
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
dt2.Merge(dt1,true);
}
What about this:
DataRow[] rows = new DataRow[dt1.Rows.Count];
dt1.Rows.CopyTo(rows, 0);
foreach (DataRow row in rows)
{
dt2.Rows.Add(row);
}
i'm assuming your tables have the same structure
foreach (DataRow row in dt1.Rows)
dt2.Rows.Add(row.ItemArray);
How can I export GridView.DataSource to datatable or dataset?
Assuming your DataSource is of type DataTable, you can just do this:
myGridView.DataSource as DataTable
You should convert first DataSource in BindingSource, look example
BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource
DataTable tCxC = (DataTable) bs.DataSource;
With the data of tCxC you can do anything.
Personally I would go with:
DataTable tbl = Gridview1.DataSource as DataTable;
This would allow you to test for null as this results in either DataTable object or null. Casting it as a DataTable using (DataTable)Gridview1.DataSource would cause a crashing error in case the DataSource is actually a DataSet or even some kind of collection.
Supporting Documentation: MSDN Documentation on "as"
Ambu,
I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.
DataTable dt = new DataTable();
// add the columns to the datatable
if (GridView1.HeaderRow != null)
{
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
// add the footer row to the table
if (GridView1.FooterRow != null)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
{
dr[i] = GridView1.FooterRow.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
If you do gridview.bind() at:
if(!IsPostBack)
{
//your gridview bind code here...
}
Then you can use DataTable dt = Gridview1.DataSource as DataTable; in function to retrieve datatable.
But I bind the datatable to gridview when i click button, and recording to Microsoft document:
HTTP is a stateless protocol. This means that a Web server treats each
HTTP request for a page as an independent request. The server retains
no knowledge of variable values that were used during previous
requests.
If you have same condition, then i will recommend you to use Session to persist the value.
Session["oldData"]=Gridview1.DataSource;
After that you can recall the value when the page postback again.
DataTable dt=(DataTable)Session["oldData"];
References:
https://msdn.microsoft.com/en-us/library/ms178581(v=vs.110).aspx#Anchor_0
https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/
I have used below line of code and it works, Try this
DataTable dt = dataSource.Tables[0];
This comes in late but was quite helpful. I am Just posting for future reference
DataTable dt = new DataTable();
Data.DataView dv = default(Data.DataView);
dv = (Data.DataView)ds.Select(DataSourceSelectArguments.Empty);
dt = dv.ToTable();