在DataGrid里添加编辑和删除按纽列
对DataGrid的数据源里的进行删除更新操作...然后再重新绑定....
可一点删除或更新,他总提示脚本错误:_EVENTTARGET为空或不是对象
查了很多地方还是没找到答案,希望高手帮帮我,谢谢!

解决方案 »

  1.   

    private void BindtoDataGrid1()
    {
    string userID = (string)Session["user"];
    SqlConnection con = DB.createCon();
    SqlDataAdapter sda = new SqlDataAdapter();
    sda.SelectCommand = new SqlCommand("select * from StockPrice where  userID='"+userID+"'",con);
    DataSet ds = new DataSet();
    sda.Fill(ds,"StockPrice");
    this.DataGrid1.DataKeyField="ruleID";
    this.DataGrid1.DataSource=ds.Tables["StockPrice"]; this.DataGrid1.DataBind();
    con.Close();
    }
    private void DataGrid1_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    string ruleID = this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
    SqlConnection con = DB.createCon();
    SqlCommand cmd = new SqlCommand("delete from StockPrice where ruleID='" + ruleID + "'",con);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    this.BindtoDataGrid1();
    }private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
    if(e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
    {
             e.Item.Attributes.Add("onmouseover","c=this.style.backgroundColor;this.style.backgroundColor='#6699ff'");
    e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=c;");
    ((LinkButton)(e.Item.Cells[5].Controls[0])).Attributes.Add("onclick","return confirm('确认删除?');");
    }
    }private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
    {
    this.DataGrid1.CurrentPageIndex=e.NewPageIndex;
    this.BindtoDataGrid1();
    }private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
    this.BindtoDataGrid1();
    }
    private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
    string ruleID = this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
    float stockLowPrice = Convert.ToSingle(((TextBox)(e.Item.Cells[1].Controls[1])).Text);
    float stockHighPrice = Convert.ToSingle(((TextBox)(e.Item.Cells[2].Controls[1])).Text);
    int SendTimes = Convert.ToInt32(((DropDownList)(e.Item.Cells[3].Controls[1])).SelectedValue);
    SqlConnection con = DB.createCon();
    con.Open();
    SqlCommand cmd = new SqlCommand("update StockPrice set stockLowPrice="+stockLowPrice+",stockHighPrice="+stockHighPrice+
    ",SendTimes="+SendTimes+" where ruleID='"+ruleID+"'",con);
    cmd.ExecuteNonQuery();
    con.Close();
    this.DataGrid1.EditItemIndex=-1;
    this.BindtoDataGrid1();}
      

  2.   

    <asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="5"
    CellPadding="3" BackColor="White" BorderWidth="1px" BorderStyle="None" BorderColor="#CCCCCC">
    <SelectedItemStyle Font-Size="13px" Font-Bold="True" ForeColor="White" BackColor="#669999"></SelectedItemStyle>
    <EditItemStyle Font-Size="13px"></EditItemStyle>
    <AlternatingItemStyle Font-Size="13px"></AlternatingItemStyle>
    <ItemStyle Font-Size="13px" ForeColor="#000066"></ItemStyle>
    <HeaderStyle Font-Size="15px" Font-Bold="True" HorizontalAlign="Center" ForeColor="White" BackColor="#006699"></HeaderStyle>
    <FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
    <Columns>
    <asp:BoundColumn DataField="stockID" ReadOnly="True" HeaderText="股票代码">
    <HeaderStyle Width="80px"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    </asp:BoundColumn>
    <asp:TemplateColumn HeaderText="股价低值">
    <HeaderStyle Width="80px"></HeaderStyle>
    <ItemStyle HorizontalAlign="Right"></ItemStyle>
    <ItemTemplate>
    <asp:Label id=Label1 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.stockLowPrice") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox id=txtLowPrice runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.stockLowPrice") %>' Width="70px">
    </asp:TextBox>
    <asp:CompareValidator id="CompareValidator1" runat="server" Display="Dynamic" ControlToValidate="txtLowPrice"
    Operator="DataTypeCheck" Type="Double" ErrorMessage="股价低值是一个浮点数">*</asp:CompareValidator>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="股票高值">
    <HeaderStyle Width="80px"></HeaderStyle>
    <ItemStyle HorizontalAlign="Right"></ItemStyle>
    <ItemTemplate>
    <asp:Label id=Label2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.stockHighPrice") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox id=txtHighPrice runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.stockHighPrice") %>' Width="70px">
    </asp:TextBox>
    <asp:CompareValidator id="CompareValidator2" runat="server" Display="Dynamic" ControlToValidate="txtHighPrice"
    Operator="DataTypeCheck" Type="Double" ErrorMessage="股票高值是一个浮点数">*</asp:CompareValidator>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="提醒次数">
    <HeaderStyle Width="80px"></HeaderStyle>
    <ItemStyle HorizontalAlign="Center"></ItemStyle>
    <ItemTemplate>
    <asp:Label id=Label3 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.SendTimes") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:DropDownList id="ddlSendTimes" runat="server" Width="70px">
    <asp:ListItem Value="1">仅一次</asp:ListItem>
    <asp:ListItem Value="5">5次</asp:ListItem>
    <asp:ListItem Value="10">10次</asp:ListItem>
    <asp:ListItem Value="-1">无限次</asp:ListItem>
    </asp:DropDownList>
    </EditItemTemplate>
    </asp:TemplateColumn>
    <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" CancelText="取消" EditText="编辑">
    <HeaderStyle Width="70px"></HeaderStyle>
    </asp:EditCommandColumn>
    <asp:ButtonColumn Text="删除" CommandName="Delete">
    <HeaderStyle Width="40px"></HeaderStyle>
      

  3.   

    </asp:ButtonColumn>
    </Columns>
    <PagerStyle NextPageText="下一页" Font-Size="12px" PrevPageText="上一页" HorizontalAlign="Left" ForeColor="#000066"
    BackColor="PowderBlue"></PagerStyle>
    </asp:DataGrid>
      

  4.   

    <asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="5"
    CellPadding="3" BackColor="White" BorderWidth="1px" BorderStyle="None" BorderColor="#CCCCCC">显然你的datagrid没有设置datakeyfield的属性,比如你的标识列的字段是id那么设 DataKeyField="id"那么
    string ruleID = this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();
    这句怎么可能获得值捏?呵呵。要设置一下.
      

  5.   

    另外好像BindtoDataGrid1()
    也少了this.DataGrid1.DataBind();
      

  6.   

    谢谢楼上~
    但,我在BindtoDataGrid1()方法里设置了datakeyfield属性的还有一点我想补冲一下,我刚写好程序时是没有问提可以更新删除的
    后来莫名其妙的出了上面的问提,他说本地的脚本错误private void BindtoDataGrid1()
    {
    string userID = (string)Session["user"];
    SqlConnection con = DB.createCon();
    SqlDataAdapter sda = new SqlDataAdapter();
    sda.SelectCommand = new SqlCommand("select * from StockPrice where  userID='"+userID+"'",con);
    DataSet ds = new DataSet();
    sda.Fill(ds,"StockPrice");
    this.DataGrid1.DataKeyField="ruleID";
    this.DataGrid1.DataSource=ds.Tables["StockPrice"];this.DataGrid1.DataBind();
    con.Close();
    }
      

  7.   

    你没有写出你的代码,很难猜测,一个例子,你看看吧
    1. *.aspx页面中代码
      <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" CancelText="取消" EditText="編輯">
    <HeaderStyle ></HeaderStyle>
    </asp:EditCommandColumn>
    <asp:ButtonColumn Text="刪除" CommandName="delete">
    <HeaderStyle ></HeaderStyle>
    </asp:ButtonColumn>2. *.cs中的代码
       private void grdSellGoods_UpdateCommand(object source, DataGridCommandEventArgs e)
    {

    if(this.ViewState["dtSaleGoods"] != null)
    {
    dtSaleGoods = (DataTable)(this.ViewState["dtSaleGoods"]);
    }
    string strAccount  = ((TextBox)e.Item.FindControl("txtEditAccount")).Text.Trim();
    string strPiNumber = ((TextBox)e.Item.FindControl("txtEditPiNumber")).Text.Trim();
    string strRe   = ((TextBox)e.Item.FindControl("txtEditRe")).Text.Trim(); if(strGoodsID.Trim().Length == 0)    
    {    
    this.Response.Write("<script language=\"javascript\">alert('" + _GoodsNoNull + "');</script>");
    return;
    }
    if(strAccount.Trim().Length == 0)    
    {    
    this.Response.Write("<script language=\"javascript\">alert('" + _GoodsAccountNoNull + "');</script>");
    return;
    }
    if(!Function.JudgeInteger(strAccount))
    {
    this.divShowPrompt.InnerHtml = this.GetPromptInfoHtml(Xframe.WebUI.EnumPromptInfoType.Warn,Xframe.WebUI.EnumProcType.Other,this._Account + this._MustInteger +"!","",false,0);
    return;
    }            

    DataSet dsGoodsInf = new DataSet();

    DataRow drEdit = dtSaleGoods.Rows[e.Item.ItemIndex];
    drEdit["GoodsID" ]  = strGoodsID;
    drEdit["ChiName"]   = dsGoodsInf.Tables[0].Rows[0]["ChiName"].ToString();
    drEdit["Account" ]  = strAccount;
    drEdit["PiNumber"]  = strPiNumber;
    drEdit["Price"]     = decPrice;
    drEdit["sum" ]      = decPrice * decimal.Parse(strAccount);
    drEdit["Re" ]   = strRe;

    dtSaleGoods.AcceptChanges();

    this.grdSellGoods.EditItemIndex = -1;
    this.ViewState["dtSaleGoods"] = dtSaleGoods;
    this.FromViewStateBind();
    } private void grdSellGoods_CancelCommand(object source, DataGridCommandEventArgs e)
    {
    this.grdSellGoods.EditItemIndex = -1;
    this.FromViewStateBind();
    } private void grdSellGoods_EditCommand(object source, DataGridCommandEventArgs e)
    {
    this.grdSellGoods.EditItemIndex = e.Item.ItemIndex;
    this.FromViewStateBind();
    }
      

  8.   

    http://www.cnblogs.com/xiaotaoliang/archive/2005/03/29/127576.html不好意思,上面没看清楚.呵呵,是BUG了,你看看是不是这个问题
      

  9.   

    hackate:
       我看了那篇BLOG,我这儿<body>没问题啊,有结束的大于号
       不过还是多谢你!
      

  10.   

    你这样吧!这个估计是BUG,你如果有可能的话..
    新建个页面,然后把前台代码一些拷过去.然后后台代码别直接拷贝过去,因为会有些不同.你比如可以选择,选择deletecommand事件,然后他在对应后台就出现那个事件方法让你写代码,你再到原先的.CS里把对应里面的代码拷过去,以此类推..都拷贝过去,运行看看是否可以了,应该没问题.
      

  11.   

    谢谢hackate,但我试了后还是不行,
    我都晕了~
      

  12.   

    删除和更新要有个名称,,
    --------------------------------
    编辑在
    Private Sub DataGrid_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid.EditCommandEnd sub
    --------------------------------------
    更新
    Private Sub DataGrid_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid.UpdateCommandEnd sub-----------------------------------
    取消
    Private Sub DataGrid_CancelCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid.CancelCommandEnd Sub
    .....你这些函数没有去设当然不行了...
      

  13.   

    Private Sub grd_CancelCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles grd.CancelCommand
            grd.EditItemIndex = -1
            display()
        End Sub    Private Sub grd_DeleteCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles grd.DeleteCommand
            '点击“删除按扭”
            Try
                Dim sql As String
                sql = "delete timelog where id='" & e.Item.Cells(0).Text & "'"
                If UpdateData(sql) Then
                    Response.Write(ChickScript("删除成功!"))
                Else
                    Response.Write(ChickScript("删除不成功!"))
                End If
            Catch ex As Exception        End Try
            grd.EditItemIndex = -1
            display()
        End Sub    Private Sub grd_EditCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles grd.EditCommand
            grd.EditItemIndex = e.Item.ItemIndex
            display()
        End Sub    Private Sub grd_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles grd.UpdateCommand
            '点击“更新”按扭
            Dim SQL As String
            Try
                'Dim LogD As String = CType(e.Item.Cells(4).Controls(1), TextBox).Text
                'Dim AP As String = CType(e.Item.Cells(2).Controls(1), DropDownList).SelectedValue
                'Dim StartD = CType(e.Item.Cells(3).Controls(1), TextBox).Text
                Dim StateStart As String = CType(e.Item.Cells(4).Controls(1), DropDownList).SelectedValue
                'Dim EndD As String = CType(e.Item.Cells(5).Controls(1), TextBox).Text
                Dim StateEnd As String = CType(e.Item.Cells(6).Controls(1), DropDownList).SelectedValue
                Dim Sign As String = CType(e.Item.Cells(7).Controls(1), DropDownList).SelectedValue
                'Dim LogBy As String = CType(e.Item.Cells(7).Controls(1), TextBox).Text
                Dim ID As String = e.Item.Cells(0).Text            SQL = "UPDATE TimeLog SET StateStart='{0}',StateEnd='{1}',Sign='{2}' WHERE ID={3}"
                SQL = String.Format(SQL, StateStart, StateEnd, Sign, ID)            If UpdateData(SQL) = False Then
                    Response.Write(ChickScript("更新不成功!"))
                End If
            Catch ex As Exception
                LogError("workedit.aspx :更新出错:" ,ex)
            End Try
            grd.EditItemIndex = -1
            display()
        End Sub    Private Sub grd_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles grd.PageIndexChanged
            grd.CurrentPageIndex = e.NewPageIndex
            display()
        End Sub    Private Sub grd_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles grd.ItemCreated
            Try
                Select Case e.Item.ItemType
                    Case ListItemType.Item, ListItemType.AlternatingItem, ListItemType.EditItem
                        '确认是否删除
                        Dim myTableCell As TableCell
                        myTableCell = e.Item.Cells(10) '其中数字9是"删除"按纽所处单元格的位置
                        Dim myDeleteButton As LinkButton
                        myDeleteButton = myTableCell.Controls(0)
                        myDeleteButton.Attributes.Add("onclick", "return confirm('请确认是否真的要删除该记录?');")
                End Select
            Catch ex As Exception
                LogError("workedit.aspx 增加删除确认按钮时出错:" ,ex)
            End Try
        End Sub    Private Sub grd_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles grd.ItemCommand
            '脚注中的新增按钮
            If (e.CommandName = "Insert") Then
                Try
                    Dim sql As String
                    Dim f1 As TextBox = CType(e.Item.FindControl("insert01"), TextBox) '上班日期
                    Dim f2 As DropDownList = CType(e.Item.FindControl("insert02"), DropDownList) '午别
                    Dim f3 As TextBox = CType(e.Item.FindControl("insert03"), TextBox) '上班时间
                    Dim f4 As DropDownList = CType(e.Item.FindControl("insert04"), DropDownList) '上班状态
                    Dim f5 As TextBox = CType(e.Item.FindControl("insert05"), TextBox) '下班时间
                    Dim f6 As DropDownList = CType(e.Item.FindControl("insert06"), DropDownList) '下班状态
                    Dim f7 As DropDownList = CType(e.Item.FindControl("insert07"), DropDownList) '标识                sql = "insert into timelog(logd,startd,statestart,endd,stateend,ap,logby,sign) values('" & f1.Text & "','" & f3.Text & "','" & f4.SelectedValue & "','" & f5.Text & "','" & f6.SelectedValue & "','" & f2.SelectedValue & "','" & userid.Text & "'," & f7.SelectedValue & ")"
                    If UpdateData(sql) = False Then
                        Response.Write(ChickScript("新增不成功!"))
                    End If
                Catch ex As Exception
                    LogError("workedit.aspx新增记录出错:" ,ex)
                End Try
            End If
            display()
        End Sub    Private Sub grd_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles grd.ItemDataBound
            '添加编辑时列表框下拉选择功能
            Try
                'If e.Item.Cells(7).Text = "" Then
                '    Select Case CType(e.Item.Cells(7).Controls(1), Label).Text
                '        Case 0
                '            CType(e.Item.Cells(7).Controls(1), Label).Text = "正常"
                '        Case 1
                '            CType(e.Item.Cells(7).Controls(1), Label).Text = "调休"
                '        Case 2
                '            CType(e.Item.Cells(7).Controls(1), Label).Text = "请假"
                '        Case 3
                '            CType(e.Item.Cells(7).Controls(1), Label).Text = "加班"
                '        Case 4
                '            CType(e.Item.Cells(7).Controls(1), Label).Text = "出差"
                '    End Select
                'End If
                If e.Item.ItemType = ListItemType.EditItem Then
                    Dim drv As DataRowView
                    Dim current As String
                    Dim ddl As DropDownList
                    '上班状态
                    drv = CType(e.Item.DataItem, DataRowView)
                    current = drv("StateStart").ToString()
                    ddl = CType(e.Item.FindControl("DropDownList1"), DropDownList)
                    ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(current))
                    '下班状态
                    drv = CType(e.Item.DataItem, DataRowView)
                    current = drv("StateEnd").ToString()
                    ddl = CType(e.Item.FindControl("DropDownList2"), DropDownList)
                    ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(current))
                    '标识
                    drv = CType(e.Item.DataItem, DataRowView)
                    current = drv("sign").ToString()
                    ddl = CType(e.Item.FindControl("DropDownList3"), DropDownList)
                    ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(current))
                End If
            Catch ex As Exception
                LogError("auditing/workedit.aspx:grd_ItemDataBound 出错 : ", ex)
            End Try    End Sub
      

  14.   

    ekingxu你好;
    你说的是这种设置吗?private void InitializeComponent()
    {    this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndexChanged);
    this.btnDelete1.Click += new System.EventHandler(this.btnDelete1_Click);
    this.btnDelete2.Click += new System.EventHandler(this.btnDelete2_Click);
    this.btnDelete3.Click += new System.EventHandler(this.btnDelete3_Click);
    this.btnDelete4.Click += new System.EventHandler(this.btnDelete4_Click);
    this.Load += new System.EventHandler(this.Page_Load);