Trying to get second row from DataTable - c#

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

Related

how to check the datatable row column value using ado.net

i want to check the column value of one table. want to check the column value = 1 or not.in the table row column has value of 1 but not entering in the if condition.
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows[0][1].ToString()=="1") // getting false
{
InsertSmsDetails();
}
data
888a1e5 1 voltage level is critical
var list_ids = (from DataRow dr in dt.Rows
where (string)dr["ColumnName"] == "1"
select (string)dr["ColumnName"]).ToList();
foreach (var item in list_ids)
{
InsertSmsDetails();
}

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

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

Inserting records from datatable into list

I am using datatable to retrieve 1000 records from mysql database. I want to copy each record as it is to list. But I do not know the exact syntax for that.
Here is the following code I am trying to retrieve:
cmdmysql.CommandText = "select * from marctest.spectrum";
conn.Open();
MySqlDataAdapter da = new MySqlDataAdapter(cmdmysql.CommandText, conn);
//MySqlDataReader reader;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataMember = dt.TableName;
// row = dataGridView1.DataSource.ToString();
//row = dt.TableName;
MySqlDataReader reader;
reader = cmdmysql.ExecuteReader();
List<string> mylist = new List<string>();
foreach(DataRow row1 in dt.Rows)
{
mylist.Add(dt.Rows.ToString());
}
textBox1.Text = mylist.ToString();
Does anybody have an idea regarding the same? This is my actual code...
I'm not sure that doing DataRow.ToString() is going to get you anything useful (most likely just the object type).
If you want the data from each row as a string (perhaps tab-delimited?), you can try:
foreach(DataRow row1 in dt.Rows) {
StringBuilder sb = new StringBuilder();
foreach(DataColumn col in dt.Columns) {
sb.Append(row1[col].ToString();
sb.Append('\t');
}
mylist.Add(sb.ToString());
}
This will croak, if any of your column's have a null value so you may want to handle that.
Assuming that dt is the query result, and If you only need to convert these results to strings, then this should work:
foreach(DataRow row1 in dt.Rows)
mylist.Add(row1.ToString();

C# Adding a Datatable to a Datatable

I know that sounds really weird, but I am fairly new to C# and I am hoping you guys can help me out.
I am looping thru a DataTable, then excute a qry and get the the result into a DataTable.
Works OK for one record, but as soon as there are more records, only the last record is in the DT, which makes sense, I just do not know how to fix it. I need to have all the records in the DT.
Here is my code, any suggestions are welcome....
DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();
foreach (DataRow row in dt.Rows)
{
dt2 = ml.getRegistrationExport(row["ID"]);
}
GridView1.DataSource = dt2;
GridView1.DataBind();
If ml.getRegistrationExport is returning a datatable, then it overwrites the data as you loop through the first datatable.. You need to use dt2.merge to add all the data to the datatable. HTH.
DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();
foreach (DataRow row in dt.Rows)
{
dt2.merge(ml.getRegistrationExport(row["ID"]));
}
GridView1.DataSource = dt2;
GridView1.DataBind();
One of the problems I see is each row you are looping through you are replace dt2. So if you have 5 rows, you will replace dt2 5 times and which ever row happen to be last would rule dt2.
I would re think this.
Are what you are trying to do is add a row to dt2 for each row in the original dt?
DataTable dt = ml.getRegistration();
DataTable dt2 = new DataTable();
foreach (DataRow row in dt.Rows)
{
DataRow newRow = dt2.NewRow();
// What Does getRegistrationExport return?
// A row or series of rows or a new DT?
// Each would change solution
newRow["SomeColumn"] = ml.getRegistrationExport(row["ID"]);
dt2.Rows.Add(newRow);
}
GridView1.DataSource = dt2;
GridView1.DataBind();

Categories

Resources