2011-08-29 53 views
3

這是我的.cs代碼:如何使用rowdeleting事件刪除gridview中的行?

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
Gridview1.DeleteRow(e.RowIndex); 
Gridview1.DataBind(); 
} 

,這是markup

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" 
               AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting"> 
        <Columns> 
        <asp:BoundField DataField="RowNumber" HeaderText="Row Number" /> 
        <asp:TemplateField HeaderText="Column Name"> 
         <ItemTemplate> 
          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
         </ItemTemplate> 
        </asp:TemplateField> 

       <%-- <asp:TemplateField HeaderText="Header 2"> 
         <ItemTemplate> 
          <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 
         </ItemTemplate> 
        </asp:TemplateField>--%> 
        <asp:TemplateField HeaderText="Data Type"> 
         <ItemTemplate> 
           <asp:DropDownList ID="ddldatatype" runat="server"> 
           <asp:ListItem>varchar</asp:ListItem> 
           <asp:ListItem>int</asp:ListItem> 
           <asp:ListItem>numeric</asp:ListItem> 
           <asp:ListItem>uniqueidentifier</asp:ListItem> 
           <asp:ListItem>char</asp:ListItem> 
           </asp:DropDownList> 
         </ItemTemplate> 
         <FooterStyle HorizontalAlign="Right" /> 
         <FooterTemplate> 
         <asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/> 
         <asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click" /> 
         <input type="hidden" runat="server" value="0" id="hiddencount" /> 
         </FooterTemplate> 
        </asp:TemplateField> 
        <asp:TemplateField> 
         <ItemTemplate> 
          <asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" >Delete</asp:LinkButton> 
         </ItemTemplate> 
        </asp:TemplateField> 
        </Columns> 
      </asp:gridview> 

請sugegest我。我做了這麼多..但仍然沒有刪除的行...

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
     { 


      //Gridview1.DeleteRow((int)Gridview1.DataKeys[e.RowIndex].Value); 
      //Gridview1.DeleteRow(e.RowIndex); 
      //Gridview1.DataBind(); 
      foreach(DataRow dr in dt.Rows) 
      { 
       dt.Rows.Remove(dr); 
       dt.Rows[e.RowIndex].Delete(); 

      } 
      Gridview1.DeleteRow(e.RowIndex); 
      // dt = (DataTable)Gridview1.DataSource; 
      Gridview1.DataSource = dt; 
      Gridview1.DataBind(); 
     } 
+0

請提出一個問題 –

回答

1

請看下面的代碼,並做出一些改變才能得到答案的提問

<%@ Page Language="C#" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<script runat="server"> 

    void CustomersGridView_RowDeleting 
     (Object sender, GridViewDeleteEventArgs e) 
    { 
     TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2]; 
     if (cell.Text == "Beaver") 
     { 
      e.Cancel = true; 
      Message.Text = "You cannot delete customer Beaver."; 
     } 
     else 
     { 
      Message.Text = ""; 
     } 
    } 

</script> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title>GridView RowDeleting Example</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <h3> 
     GridView RowDeleting Example 
    </h3> 
    <asp:Label ID="Message" ForeColor="Red" runat="server" /> 
    <br /> 
    <asp:GridView ID="CustomersGridView" runat="server" 
     DataSourceID="CustomersSqlDataSource" 
     AutoGenerateColumns="False" 
     AutoGenerateDeleteButton="True" 
     OnRowDeleting="CustomersGridView_RowDeleting" 
     DataKeyNames="CustomerID,AddressID"> 
     <Columns> 
      <asp:BoundField DataField="FirstName" 
       HeaderText="FirstName" SortExpression="FirstName" /> 
      <asp:BoundField DataField="LastName" HeaderText="LastName" 
       SortExpression="LastName" /> 
      <asp:BoundField DataField="City" HeaderText="City" 
       SortExpression="City" /> 
      <asp:BoundField DataField="StateProvince" HeaderText="State" 
       SortExpression="StateProvince" /> 
     </Columns> 
    </asp:GridView> 
    <asp:SqlDataSource ID="CustomersSqlDataSource" runat="server" 
     SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID, 
      SalesLT.CustomerAddress.AddressID, 
      SalesLT.Customer.FirstName, 
      SalesLT.Customer.LastName, 
      SalesLT.Address.City, 
      SalesLT.Address.StateProvince 
      FROM SalesLT.Customer 
      INNER JOIN SalesLT.CustomerAddress 
      ON SalesLT.Customer.CustomerID = 
       SalesLT.CustomerAddress.CustomerID 
      INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID = 
       SalesLT.Address.AddressID" 
     DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID = 
      @CustomerID and AddressID = @AddressID" 
     ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>"> 
     <DeleteParameters> 
      <asp:Parameter Name="AddressID" /> 
      <asp:Parameter Name="CustomerID" /> 
     </DeleteParameters> 
    </asp:SqlDataSource> 
    </form> 
</body> 
</html> 
+0

我不使用的SqlDataSource ..那我應該怎麼刪除行... – Mahendra

+0

@ user913947 - 在事件處理過程將是相同的;你只需要修改你綁定的任何數據源,然後重新綁定。 – Tim

+0

我不明白你想要sya .. plz解釋或給我cde .. – Mahendra

0

我認爲你正在做的一樣因爲在這個環節提到的再結合錯誤

How to delete row from gridview?

+0

我有linkbutton ..是否有任何代碼刪除rwo從gridview ..我在做這沒有sqldatasource ..你發給我的鏈接,我讀了,但沒有滿意的代碼給我.. – Mahendra

2

你刪除代碼看起來像這樣

Gridview1.DeleteRow(e.RowIndex); 
Gridview1.DataBind(); 

當您調用Gridview1.DataBind()時,您將使用當前數據源填充您的gridview。因此,它將刪除所有現有行,並且它將添加來自CustomersSqlDataSource的所有行。

您需要做的是從CustomersSqlDataSource查詢的表中刪除該行。

通過設置到CustomersSqlDataSource的刪除命令,添加一個刪除參數,然後執行刪除命令,您可以非常容易地完成此操作。

CustomersSqlDataSource.DeleteCommand = "DELETE FROM Customer Where [email protected]"; // Customer is the name of the table where you take your data from. Maybe you named it different 
CustomersSqlDataSource.DeleteParameters.Add("CustomerID", Gridview1.DataKeys[e.RowIndex].Values["CustomerID"].ToString()); 
CustomersSqlDataSource.Delete(); 
Gridview1.DataBind(); 

但考慮到這會從數據庫中刪除數據。

+1

OP聲明他沒有使用SqlDataSource,所以這個答案(雖然正確的自己的權利)不適用於手頭的問題。 – Tim

+0

我m不是sqldatasource .. – Mahendra

+0

啊,對不起,我在看阿卜杜勒拉赫曼代碼,那裏是一個SQL數據源。那麼user913947,你在哪裏保存項目列表?你可以分享ButtonAdd_Click函數的實現嗎? – Dorin

0

如果我記得你以前的問題,你綁定到一個DataTable。試試這個:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 

    DataTable sourceData = (DataTable)GridView1.DataSource; 

    sourceData.Rows[e.RowIndex].Delete(); 

    GridVie1.DataSource = sourceData; 
    GridView1.DataBind(); 
} 

從本質上講,正如我在我的評論說,搶在GridView的DataSource的一個副本,從中取出一排,然後將數據源設置爲更新的對象,再在其上調用DataBind()。

+0

它給出了錯誤 – Mahendra

+0

未將對象引用設置爲對象的實例。 – Mahendra

+0

檢查e.RowIndex是否有值。 – Tim

7
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex]; 
    SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)"); 
    GridView1.DataBind(); 
} 
+0

當然(shirely)這是使用靜態數據表的更好選擇? 雖然不知道硬編碼的SQL命令。 – Rexxo

+3

@Rexxo實際上,這個硬編碼的SQL命令會刪除表中的所有記錄,因爲沒有Where語句。 – derloopkat

+0

Crikey,斑點! – Rexxo

7

確保創建靜態DataTable對象,然後使用下面的代碼:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
    dt.Rows.RemoveAt(e.RowIndex); 
    GridView1.DataSource = dt; 
    GridView1.DataBind(); 
} 
1

在電網使用其ID碼作爲主元素,以便唯一地標識每一行

<asp:TemplateField> 
      <ItemTemplate> 
      <asp:HiddenField ID="Hf_ID" runat="server" Value='<%# Eval("ID") %>' /> 
      </ItemTemplate> 
</asp:TemplateField> 

並且搜索uique ID使用C中的代碼背後#代碼(基本上這是搜索隱藏字段並將其存儲在一個VAR)

protected void Grd_Registration_RowDeleting(object sender, GridViewDeleteEventArgs e) 
    { 
     var ID = (HiddenField)Grd_Registration.Rows[e.RowIndex].FindControl("ID"); 
     //Your Delete Logic Goes here having ID to delete 

     GridBind(); 

    } 
+0

var id =((HiddenField)gvImages.Rows [e.RowIndex] .FindControl(「ID」))Value;' –

0

這裏是你想達到什麼把戲。我也有像你這樣的問題。

在RowDeleting事件中很難獲得選定的行和數據鍵但是在SelectedIndexChanged事件中獲取選定的行和數據鍵是非常容易的。這裏是一個例子 -

protected void gv_SelectedIndexChanged(object sender, EventArgs e) 
{ 
     int index = gv.SelectedIndex; 
     int vehicleId = Convert.ToInt32(gv.DataKeys[index].Value); 
     SqlConnection con = new SqlConnection("-----"); 
     SqlCommand com = new SqlCommand("DELETE FROM tbl WHERE vId = @vId", con); 
     com.Parameters.AddWithValue("@vId", vehicleId); 
     con.Open(); 
     com.ExecuteNonQuery(); 
} 
+0

我不建議在代碼中將數據訪問代碼放在代碼後面。 – DtechNet

1

該解決方案有點簡單,一旦你從datagrid中刪除了行(你的代碼只會從網格中刪除行而不是數據源),那麼你不需要做其他任何事情。 因爲您正在執行數據綁定操作,而不更新數據源,所以您將從源重新添加所有行到gridview控件(包括在前面的語句中從網格中移除的行)。

要簡單地從網格刪除沒有數據源,然後只需調用網格上的刪除操作,這就是所有你需要做的......之後不需要數據綁定。

3

最簡單的方法是使用ASP中的某些數據源創建GridView,並在Row_Deletinng事件中調用該數據源。例如,如果你有SqlDataSource1爲你的GridView的數據源,您Row_Deleting事件是:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
     int ID = int.Parse(GridView1.Rows[e.RowIndex].FindControl("ID").toString()); 
     string delete_command = "DELETE FROM your_table WHERE ID = " + ID; 
     SqlDataSource1.DeleteCommand = delete_command; 
} 
0

添加在頁面加載下面的線,

ViewState["GetRecords"] = dt; 

那就試試這個,

protected void DeleteRows(object sender, GridViewDeleteEventArgs e) 
{ 
    dt = ViewState["GetRecords"] as DataTable; 
    dt.Rows.RemoveAt(e.RowIndex); 
    dt.AcceptChanges(); 
    ViewState["GetRecords"] = dt; 
    BindData(); 
} 

如果您還有任何問題,請發送BindData()方法中的代碼

0
 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
    { 
     int index = GridView1.SelectedIndex; 
     int id = Convert.ToInt32(GridView1.DataKeys[index].Value); 
     SqlConnection con = new SqlConnection(str); 
     SqlCommand com = new SqlCommand("spDelete", con); 
     com.Parameters.AddWithValue("@PatientId", id); 
     con.Open(); 
     com.ExecuteNonQuery(); 

指數超出範圍。必須是非負數且小於集合的大小。 參數名稱:index

0

我知道這是一個遲到的答案,但它仍然會幫助需要解決方案的人。 我建議使用OnRowCommand和DataKeyNames一起刪除操作,並保留OnRowDeleting函數以避免異常。

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" 
    AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting" OnRowCommand="Gridview1_RowCommand" DataKeyNames="ID"> 

在gridView中包含DataKeyNames =「ID」,並在鏈接按鈕中指定相同。

<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ID")%>'>Delete</asp:LinkButton> 

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "Delete") 
    { 
     int ID = Convert.ToInt32(e.CommandArgument); 
     //now perform the delete operation using ID value 
    } 
} 

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)  
{ 
//Leave it blank 
} 

如果這是有幫助的,給我+