所有行在网格视图中都是不可见的

时间:2016-09-30 09:45:34

标签: c# asp.net c#-4.0

我写过像

这样的方法
     private void AvoidDuplicate()
    {
        for (int i = 0; i < grdView.Rows.Count; i++)
        {
            TextBox txtoldvalue = grdView.Rows[i].FindControl("txtLicenseNumber") as TextBox;
            string oldvalue = txtoldvalue.Text.ToString();

            for (int j = 0; j < grdView.Rows.Count; j++)
            {
                TextBox txtnewvalue = grdView.Rows[j].FindControl("txtLicenseNumber") as TextBox;
                string newvalue = txtnewvalue.Text.ToString();
                if (oldvalue == newvalue)
                {
                    grdView.Rows[j].Visible = false;
                }
            }
        }
    }

加载页面时调用此函数。问题在于它使gridview中的所有行都不可见。我想仅检查是否存在具有相同值的文本框,只有一行应该变为不可见。请帮忙

2 个答案:

答案 0 :(得分:0)

尝试使用字典。获取所有唯一值,然后检查字典是否包含值,如果不使其不可见

private void AvoidDuplicate()
{
  Dictionary<string,string> checkdictionary=new Dictionary<string,string>();

    for (int i = 0; i < grdView.Rows.Count; i++)
    {
        TextBox txtnewvalue = grdView.Rows[i].FindControl("txtLicenseNumber") as TextBox;
            string newvalue = txtnewvalue.Text.ToString();
        if(!checkdictionary.ContainsKey(newvalue))
        {
             checkdictionary[newvalue]="something";
        }
        else
        {
          grdView.Rows[i].Visible = false;
        }

    }
}

答案 1 :(得分:-1)

试试这个

 private void AvoidDuplicate()
        {
            for (int i = 0; i < grdView.Rows.Count; i++)
            {
                TextBox txtoldvalue = grdView.Rows[i].FindControl("txtLicenseNumber") as TextBox;
                string oldvalue = txtoldvalue.Text.ToString();

                for (int j = 0; j < grdView.Rows.Count; j++)
                {
                   if( j == i)
                     continue;
TextBox txtnewvalue = grdView.Rows[j].FindControl("txtLicenseNumber") as TextBox;
                    string newvalue = txtnewvalue.Text.ToString();
                    if (oldvalue == newvalue)
                    {
                        grdView.Rows[j].Visible = false;
                    }
                }
            }
        }

更简单的方法是,使用 DataView

    //populate your datatable dt. List your columns in ToTable method that you want to include in uniqueness of row.

    dt = dt.DefaultView.ToTable(true, "LicenseNumber");
    GridView1.DataSource = dt;
    GridView1.DataBind();