How to bind DataRow to the GridView? - c#

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;

Related

How to display specific row of data based on a column value

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

Get a selected Row of DataGridView as a DataRow

I have a datagridview that filled by a DataTable's Data; I want to get DataGridView's current selected row and pass this row as a DataRow to another form in dataGridView1_CellDoubleClick Event of my DataGridView.
I tried this code:
int rw = dataGridView1.CurrentRow.Index
DataRow PassingSessionInfo;
PassingSessionInfo = SessionsData.NewRow();
PassingSessionInfo = dataGridView1.Rows[rw];
and SessionsInfo is a DataTable.
I Got error, could you please help me?
Try this code:
int rw = dataGridView1.CurrentRow.Index
DataRow PassingSessionInfo;
PassingSessionInfo = ((dataGridView1.DataSource) as DataTable).Rows[rw];
PLease Try
int rw = dataGridView1.CurrentRow.Index
DataRow PassingSessionInfo;
PassingSessionInfo = SessionsData.NewRow();
DataTable dt = (DataTable)dataGridView1.DataSource;
dt.Rows.Add(dataGridView1.Rows[rw]);
PassingSessionInfo = dt.Rows[0];

copying values of a dataTable to another DataTable with different clumns

I have a DataTable dt1 that contains this columns : PRODUCT_ID,MIN_VALUE,MAX_VALUE,AMOUNT
and another DataTable dt2 that contains this columns : ID,MIN,MAX,POINT_TO_ADD
dt1 contains multiple rows that I want to copy them to dt2 how can I do that ?
try this
foreach (DataRow sourcerow in dt1.Rows)
{
DataRow destRow = dt2.NewRow();
destRow["ID"] = sourcerow["PRODUCT_ID"];
destRow["MIN"] = sourcerow["MIN_VALUE"];
destRow["MAX"] = sourcerow["MAX_VALUE"];
destRow["POINT_TO_ADD"] = sourcerow["AMOUNT"];
dt2.Rows.Add(destRow);
}
Try this:
for(int i=0;i<dt1.Rows.Count;i++){
DataRow dr = dt2.NewRow();
dr["ID"] = dt1.Rows[i]["PRODUCT_ID"];
dr["MIN"] = dt1.Rows[i]["MIN_VALUE"];
dr["MAX"] = dt1.Rows[i]["MAX_VALUE"];
dr["POINT_TO_ADD"] = dt1.Rows[i]["AMOUNT"];
dt2.Rows.Add(dr);
}

Delete Row From Data 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);

Listview to datatable

I have a listview and I NEED to load the rows and columns into datatable.
I have tried as follows
DataTable dt = new DataTable();
foreach (ListViewItem item in listView1.Items)
{
table.Columns.Add(item.ToString());
foreach (var it in item.SubItems)
dt.Rows.Add(it.ToString());
}
When I retrieved the rowcount and columncount then I got number of rows as column count and number of column as rowcount
dont know what's going on..
please help me
best regards
Bunzitop
its a long time ago, but someone will probably struggle about this in the future,
so here is my solution to convert a ListView to a DataTable:
DataTable dtZeitplan = new DataTable();
foreach (ColumnHeader chZeitplan in lvZeitplan.Columns)
{
dtZeitplan.Columns.Add(chZeitplan.Text);
}
foreach (ListViewItem item in lvZeitplan.Items)
{
DataRow row = dtZeitplan.NewRow();
for(int i = 0; i < item.SubItems.Count; i++)
{
row[i] = item.SubItems[i].Text;
}
dtZeitplan.Rows.Add(row);
}
You are doing it so wrong. You need 1 + listView1.Items[0].SubItems.Count columns in your DataTable (the 1 is for ListViewItem and others are subitems) and listView1.Items.Count number of rows. Therefore your code should be like this:
if (listView1.Items.Count > 0)
{
dt.Columns.Add();
foreach (ListViewItem.ListViewSubItem lvsi in listView1.Items[0].SubItems)
dt.Columns.Add();
//now we have all the columns that we need, let's add rows
foreach (ListViewItem item in listView1.Items)
{
List<string> row = new List<string>();
row.Add(item.ToString());
foreach (var it in item.SubItems)
row.Add(it.ToString());
//Add the row into the DataTable
dt.Rows.Add(row.ToArray());
}
}
DataTable table = new DataTable();
table.Columns.Add("MODUL", typeof(string));
table.Columns.Add("ACIKLAMA", typeof(string));
table.Columns.Add("UZUNLUK", typeof(string));
table.Columns.Add("GENISLIK", typeof(string));
table.Columns.Add("MIKTAR", typeof(string));
for (int i = 0; i < listView2.Items.Count; i++)
{
table.Rows.Add(listView2.Items[i].SubItems[1].Text, listView2.Items[i].SubItems[2].Text, listView2.Items[i].SubItems[3].Text, listView2.Items[i].SubItems[4].Text, listView2.Items[i].SubItems[5].Text);
}
You can use the ItemsSource property and System.Data classes (ADO.Net) to bind a listview to a datatable and vise-verse (what you want). The following code will give you a datatable from an existing bound ListView control.
DataView theDataView = (DataView)theListView.ItemsSource;
DataTable theDataTable = theDataView.Table;
Manish Mishra asked what your listview control is bound to. This is a very good question. My answer assumes it is already bound to a datatable.
Working code from VB.Net: Just replace your listview name with "LVActions"
Dim it As Integer = 0
Dim dt As New DataTable
For it = 0 To LVActions.Items(0).SubItems.Count - 1
Dim DCOL As New DataColumn(LVActions.Columns(it).Text)
dt.Columns.Add(DCOL)
Next
For it = 0 To LVActions.Items.Count - 1
Dim DROW As DataRow = dt.NewRow
For j As Integer = 0 To LVActions.Items(it).SubItems.Count - 1
DROW(LVActions.Columns(j).Text) = LVActions.Items(it).SubItems(j).Text
Next
dt.Rows.Add(DROW)
Next

Categories

Resources