日期:2014-05-17  浏览次数:20938 次

gridview更新数据的问题?
平台:VS2010 WEB项目 SQL2008
数据表:如下在gridview中显示
 ID  Name Age TEL 
10001  小李  28 13888888888 更新
10002  小张  28 13866666666 更新
10003  小王  55 13888888888 更新
上面三条数据是我添加到数据库的数据.
一,在WEB页面中添加数据时,已经判断数据库NAME列不能重复,其他列是可以重复的.
二,现在我要对10003这条数据进行更新,NAME列的小王,我修改成小李,是可以更新的.当然这不是我要的效

果,如果修改成小李,NAME列就重复了(我用添加数据同样的方法去判断NAME重复性,就不能修改AGE,TEL列

了).
我要的效果是:
1.点10003这条数据进行更新,小王是不能修改成数据库NAME列相同名称的.小王可以修改成小蒋,小刘都可

以,就是不能修改成小李,小张.
2.点10003这条数据进行更新,小王可以不修改,但可以修改AGE,TEL这两列的数据.
3.以上两条要同时满足,我应该怎么做?在此先谢过!所有分送上.

------解决方案--------------------
点击编辑的时候将name那一列设为只读
------解决方案--------------------
<asp:TemplateField>
                <EditItemTemplate>
                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    <%--编辑状态下为label或textbox的 ReadOnly="true"--%>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>

------解决方案--------------------
你可以类似这样,但是建议用参数化查询会更好些,呵呵

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

            GridViewRow myRow = GridView1.Rows[e.RowIndex];
    TextBox id = myRow.Cells[1].FindControl("txtId") as TextBox;
    TextBox name = myRow.Cells[2].FindControl("txtName") as TextBox;
    //判断数据重复
    string sql="select * from table1 where name='"+name+"' and id<>'"+id+"'";
    DataTable dt=DBHelper.GetTable(sql);
    if(dt.Rows.count==0)
    {
//如果不重复则更新数据
sql="update table1 set name='"+name+"' where id='"+id+"'";
int rows=DBHelper.ExecuteNonQuery(sql);
if(rows==1)
{
   //更新成功
   GridView1.EditIndex = -1;
   //重新绑定
   DataBind();
}
}
------解决方案--------------------
改成小李以后
//判断数据重复
    string sql="select * from table1 where name='"+name+"' and id<>'"+id+"'";
这个sql的就会返回>1的数据,所以就是重复了,你可以试试
------解决方案--------------------
你让他随便改。但是更新之前先做存在check,如果不存在才可以将名字改成修改后的名字。比如说小蒋,如果已经有小李了。就不能修改成小李。但是别的数据可以更新。