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

时间:2016-08-31 17:53:03

标签: c# asp.net datatable json.net

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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;