ado.net PrimaryKey 判断插入数据是否已经存在

 

protected DataTable GetDataFromGridView()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ID", typeof(System.String));
        dt.Columns.Add("name", typeof(System.String));
        dt.Columns.Add("sort", typeof(System.String));
        dt.PrimaryKey = new DataColumn[] { dt.Columns[1] };
        int rowIndex = 0;

        foreach (GridViewRow item in gvJXZYDW.Rows)
        {
            DataRow dr = dt.NewRow();
            dr[0] = gvJXZYDW.DataKeys[rowIndex][0].ToString();
            string txtDwmc = ((TextBox)item.FindControl("txtName")).Text.Trim();
            if (dt.Rows.Contains(txtDwmc))
            {
                MessageBox.Show( ":已经存在!");
                return dt;
            }
            else
            {
                dr[1] = ((TextBox)item.FindControl("txtName")).Text.Trim();
            }
            dr[2] = ((TextBox)item.FindControl("txtSort")).Text.Trim();
            dt.Rows.Add(dr);
            rowIndex++;
        }
        return dt;
    }

但愿有人能用得着。

你可能感兴趣的:(primary)