【问题标题】:How to display specific row of data based on a column value如何根据列值显示特定的数据行
【发布时间】:2016-08-31 17:53:03
【问题描述】:

从此代码中,我试图仅显示包含Station_From_Code 列中的“DBY”字段和Station_To_Column 中的“MAT”字段的数据行。然后将其打印到 HTML 页面上。这些字段肯定在数据表中,但是当我运行这个代码时,表是空的。我不习惯在 C# 中使用数据表,因此对糟糕的编码表示歉意。

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

【问题讨论】:

  • 您是否尝试过仅使用通配符并选择所有行以确保您得到结果并且您的连接良好?
  • 你能解释一下什么是停止吗?
  • 我添加了更多代码
  • 您的代码错误。每次迭代都会更改 DataSource!

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


【解决方案1】:

很久没见过这种处理数据库表的代码了! EntityFramework 发生了变化,肯定会简化使用数据库的方式,并防止在代码中使用 SQL 命令的不同风险。

如果你使用 EF,你的代码会变成下面这样:

var rows = myDBContext.MyTable.Where(x=>x.From_Station_Code == "DBY" && x.To_Station_Code == "MAT");
GridViewTrainTimes.DataSource = rows;

【讨论】:

    【解决方案2】:

    您可以使用查找匹配行并添加仅包含匹配行数据的新数据表,然后您可以将此 dt 绑定到 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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2019-03-30
      • 2019-05-07
      相关资源
      最近更新 更多