在插入gridview之前找到重复项

时间:2017-01-09 10:29:41

标签: c# asp.net

如何在插入gridview之前检查,我的插入代码在按钮下方点击。

if (Session["dtInSession"] != null)
    dt1 = (DataTable)Session["dtInSession"];
    DataRow dr = dt1.NewRow();
    dr["AccessoryName"] = drpAccessories.SelectedItem;
    dr["ConditionName"] = drpConditions.SelectedItem;
    dt1.Rows.Add(dr);
    Session["dtInSession"] = dt1; 
    ViewState["CurrentTable"] = dt1;
    grvList.DataSource = dt1;
    grvList.DataBind();

我试过这种方式但是肯定它只检查最后选择的项而不是已插入的其他行。

if (grvList.Rows.Count > 0)
{
  foreach (GridViewRow gr in grvList.Rows)
  {
    accessorucheck = ((Label)gr.FindControl("txtAccessories")).Text;
    if (accessorucheck == drpAccessories.Text)
    {
      ClientScript.RegisterStartupScript(Page.GetType(), "validation1", "<script language='javascript'>alert('Accessory Alredy Added, Please change the condition if needed.')</script>");
    }
    else
    {
      if (Session["dtInSession"] != null)
        dt1 = (DataTable)Session["dtInSession"];
        DataRow dr = dt1.NewRow();
        dr["AccessoryName"] = drpAccessories.SelectedItem;
        dr["ConditionName"] = drpConditions.SelectedItem;
        dt1.Rows.Add(dr);
        Session["dtInSession"] = dt1;
        grvList.DataSource = dt1;
        grvList.DataBind();
    }
  }
}

2 个答案:

答案 0 :(得分:1)

你可以按照ihtsham上面提到的方式进行操作,但是你仍会最​​终插入一条记录,然后再次省略,增加了不必要的开销。

我宁愿在从会话变量获取数据表之后使用select命令检查是否存在这样的行。你可以使用类似的东西,不要认为语法会很完美,因为我的ASP.Net生锈了,但它应该让你走上正轨。

if (dt2.Select("AccessoryName = 'Var' AND ConditionName = 'Var2'").Rows.Count == 0)
{
   //Insert code here
}
else
{
   //Code to execute when duplicate added
}

答案 1 :(得分:0)

您可以使用DataView.ToTable MSDN DataView.ToTable

if (Session["dtInSession"] != null)
        dt1 = (DataTable)Session["dtInSession"];

    DataRow dr = dt1.NewRow();
    dr["AccessoryName"] = drpAccessories.SelectedItem;
    dr["ConditionName"] = drpConditions.SelectedItem;
    dt1.Rows.Add(dr);
    Session["dtInSession"] = dt1; 
    ViewState["CurrentTable"] = dt1;
// 
DataView view = new DataView(dt1);
DataTable distinctValues = view.ToTable(true, "AccessoryName", "ConditionName");
grvList.DataSource = distinctValues;
grvList.DataBind();