在datagrid中添加了删除功能,却发现删除按下去无反映前台已经设置 keyfield=id ,com name = detele   删除按钮是datagird控件中添加的 能查的都查过了就是找不道原因,已经附上注释代码请各位高手指点小弟,感激不尽
前台datagird 部分代码

<form id="form1" method="post" runat="server"><asp:datagrid id="DataGrid1" runat="server" Width="533px" AutoGenerateColumns="False" DataKeyField="id"><ItemStyle Font-Size="12px"></ItemStyle>
<HeaderStyle Font-Size="12px"></HeaderStyle>
<Columns>
<asp:BoundColumn DataField="id" HeaderText="id"></asp:BoundColumn>
<asp:BoundColumn DataField="title" HeaderText="意见主题"></asp:BoundColumn>
<asp:BoundColumn DataField="wd" HeaderText="状态"></asp:BoundColumn>
<asp:BoundColumn DataField="CreatedOn" HeaderText="日期"></asp:BoundColumn>
<asp:HyperLinkColumn Text="查看" Target="_blank" DataNavigateUrlField="id" DataNavigateUrlFormatString="Up_message.aspx?id={0}"
HeaderText="查看"></asp:HyperLinkColumn>
<asp:ButtonColumn Text="删除" HeaderText="删除" CommandName="Delete"></asp:ButtonColumn>
</Columns>
</asp:datagrid>
<asp:dropdownlist id="DropDownList1" runat="server" DataTextFormatString="name" DataValueField="name"></asp:dropdownlist></td>
后台代码using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;namespace shinan
{ public class message : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected SqlConnection con;
protected System.Web.UI.WebControls.TextBox title;
protected System.Web.UI.WebControls.TextBox content;
protected DataTable dt=null;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected string canshu;
protected SqlDataAdapter ada;
                protected SqlDataAdapter sda;
protected DataSet ds=new DataSet();
protected DataSet ds1=new DataSet();
protected System.Web.UI.WebControls.DropDownList DropDownList1;
protected System.Web.UI.WebControls.Label Label1;
protected DataTable dt1=null;
protected DataTable dt3=null;
private void Page_Load(object sender, System.EventArgs e)
{
con=forcon.getcon("shinan");
    
if   (!IsPostBack) 
{     
con=forcon.getcon("shinan"); 
dt=forcon.getdt("select * from tbl_user where qx='领导'",con);
DropDownList1.DataSource=dt;
DropDownList1.DataBind();  } 
try
{
if(Request.Cookies["name"].Value==null) //如果没登陆
{
canshu="denglu.aspx";    // 登陆栏内容
DataGrid1.Visible=false; }
else   //在上面显示留言列表
{

canshu="denglu2.aspx";  // 登陆栏内容
Label1.Text = Server.UrlDecode(Request.Cookies["le"].Value);

ada=new SqlDataAdapter("select * from tbl_yj where foruser='"+ Label1.Text +"'order by CreatedOn desc ",con);
ds.Clear();
ada.Fill(ds,"tbl_yj");
dt1=ds.Tables["tbl_yj"];
DataGrid1.Visible=true;
DataGrid1.DataSource=dt1;
DataGrid1.DataBind();
}
}
catch
{
canshu="deng.aspx"; }
}
private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
forcon.getvalue("delete tbl_yj where id='"+Int32.Parse(DataGrid1.DataKeys[(int)e.Item.ItemIndex].ToString())+"'",con);
dt3=forcon.getdt("select * from tbl_yj",con);
DataGrid1.DataSource=dt3;
DataGrid1.DataBind();
} private void Button1_Click(object sender, System.EventArgs e)
{
forcon.getvalue("insert into tbl_yj values('"+title.Text+"','"+content.Text+"','"+DropDownList1.SelectedItem.Text+"',getdate(),'新意见')",con);

// 插入留言

Response.Write("<script language='Javascript'>alert('提交成功!')</script>");

}

}
}

解决方案 »

  1.   

    1 选择DataGrid自动生成的删除代码,LZ自己研究一下,很简单
    2 自己写后台代码,可用ButtonField,CommandArgument
      

  2.   

    如何使DataGrid 在后台生成代码? 只能生成前台的代码
      

  3.   

    又是一个if (!IsPostBack) 问题每次Page_Load时,都加载了这些代码:
    DataGrid1.Visible=true; 
    DataGrid1.DataSource=dt1; 
    DataGrid1.DataBind(); 
    等于你点击删除按钮无效了在Page_Load中把try那一段放到if (!IsPostBack)中去吧
      

  4.   

    [code=C#][/string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        ...{
            if (!IsPostBack)
            ...{
                GridView1.AllowSorting = true;
                BindData();
                SetGrid();
                //ViewState["style"] = "0";
            }
        }
        private void BindData()
        ...{
            
            SqlConnection MyCon = new SqlConnection(ConStr);
            string QueryStr = "SELECT customerid,CompanyName,ContactName,Address FROM customers";
            SqlDataAdapter Da = new SqlDataAdapter(QueryStr,MyCon);
            DataSet Ds = new DataSet();
            Da.Fill(Ds,"Customers");
            GridView1.DataSource = Ds.Tables[0];
            GridView1.DataKeyNames = new string []...{"customerid"};
            GridView1.DataBind();
            
        }
        private void SetGrid()
        ...{
            GridView1.AllowPaging = true;
            //GridView1.PageSize = 15;
        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        ...{
            GridView1.PageIndex = e.NewPageIndex;
            BindData();
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        ...{
            GridView1.EditIndex = e.NewEditIndex;
            GridView1.EditRowStyle.BackColor = Color.Black;
            BindData();
        }
        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        ...{
            GridView1.EditIndex = -1;
            BindData();
        }
        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        ...{
            GridViewRow Row = GridView1.Rows[e.NewSelectedIndex];
            Response.Write("<script>alert('你选择了ID为" + Row.Cells[3].Text + "的行');</script>");
        }
        protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        ...{
            Response.Write("<script>alert('你切换到了第" + (GridView1.PageIndex+1) + "页');</script>");
        }
        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        ...{
            GridViewRow Row = GridView1.SelectedRow;
            Row.BackColor = Color.Crimson;
        }
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        ...{
            string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
            //防止非法的输入,预防脚本攻击
            string CustomerId = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString());
            string CompanyName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString());
            string ContactName = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());
            string Address = Server.HtmlDecode(((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text.ToString());
            SqlConnection Con = new SqlConnection(ConStr);
            try
            ...{
                string UpdateStr = "UPDATE customers SET companyname='" + CompanyName + "',contactname='" + ContactName + "',address='" + Address + "' WHERE customerid='" + ID + "'";
                SqlCommand Cmd = new SqlCommand(UpdateStr, Con);
                //尽可能晚的打开连接,尽早的关闭连接
                Con.Open();
                Cmd.ExecuteNonQuery();
                GridView1.EditIndex = -1;
                BindData();
            }
            catch (Exception ex)
            ...{
                Response.Write("<script>alert('编辑出错,请重新填写');</script>");
                GridView1.EditIndex = -1;
                BindData();
            }
            //要及时的关闭打开的连接,提高程序的性能
            finally
            ...{
                Con.Dispose();
            }
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        ...{
            string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
            string QueryStr = "DELETE FROM customers WHERE customerid='" + ID + "'";
            SqlConnection Con = new SqlConnection(ConStr);
            SqlCommand Cmd = new SqlCommand(QueryStr,Con);
            try
            ...{
                Con.Open();
                Cmd.ExecuteNonQuery();
                BindData();
                Response.Write("<script>alert('成功删除');</script>");
            }
            catch (Exception ex)
            ...{
                Response.Write("<script>alert('删除有误,请检查该表是否与其他表有约束');</script>");
            }
            finally
            ...{
                Con.Dispose();
            }
        }
    ]
      

  5.   


    这样试试
    前台 <asp:TemplateField>
                                                    <ItemTemplate>
                                                        <asp:LinkButton ID="lk_delete" runat="server" OnClientClick ="return confirm('您真的要删除?')" CommandName="delete">删除</asp:LinkButton>
                                                    </ItemTemplate>
                                                    <ItemStyle HorizontalAlign="Center" />
                                                </asp:TemplateField>
    后台 protected void gr_worker_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SqlConnection con = new SqlConnection(DataConnection.CONNECTIONSTR);
            string sqlstr = "delete from Tb_User where User_Id='" + gr_worker.DataKeys[e.RowIndex].Value.ToString() + "'";
            com = new SqlCommand(sqlstr, con);
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
            Bind();
            GridViewDataBind();
        }
    稍微改改就能用
      

  6.   

    问题解决...是没有在insitl...里设置...双击前台即可...送分