2017-02-22 113 views
0

我在我的GridView中添加了一個刪除按鈕。但問題是它總是刪除第一行。刪除按鈕只在gridview中刪除的第一行

例如,如果我刪除第二行或第三行,第一行中的數據將被刪除。我只想按鈕刪除的行旁邊:

public void bindgrid() 
{ 
    SqlConnection conn = new SqlConnection("cnString"); 
    SqlCommand cmd = new SqlCommand("select Id,Name, from myTable ", conn); 
    SqlDataAdapter da = new SqlDataAdapter("", conn); 
    da.SelectCommand = new SqlCommand("select Id,Name, from myTable", conn); 
    DataSet ds = new DataSet(); 
    da.Fill(ds, "data"); 
    gridview1.DataSource = ds.Tables[0].DefaultView; 
    gridview1.DataBind(); 
} 


protected void gdview_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
    int userid = int.Parse(gridview1.DataKeys[0].Value.ToString()); 
    SqlConnection conn = new SqlConnection("cnString"); 
    SqlDataAdapter da = new SqlDataAdapter("", conn); 
    conn.Open(); 
    da.DeleteCommand = new SqlCommand("delete from myTable where Id=" + userid , conn); 

    da.DeleteCommand.ExecuteNonQuery(); 
    conn.Close(); 
    bindgrid(); 
} 
+0

你需要得到您單擊 –

+0

行東印度你應該尋找的GridView的選擇行,然後取該行的ID,然後去刪除part.It在我看來,你總是揪着的ID第一行 – Veljko89

回答

3

你應該該行

int userid = int.Parse(gridview1.DataKeys[0].Value.ToString()); 

傳遞,而不是gridview1.DataKeys[0]

protected void gdview_RowDeleting(object sender, GridViewDeleteEventArgs e) 
    { 
    int userid = int.Parse(gridview1.DataKeys[e.RowIndex].Value.ToString()); 
    SqlConnection conn = new SqlConnection("cnString"); 
    SqlDataAdapter da = new SqlDataAdapter("", conn); 
    conn.Open(); 
    da.DeleteCommand = new SqlCommand("delete from myTable where Id=" + userid , conn); 

    da.DeleteCommand.ExecuteNonQuery(); 
    conn.Close(); 
    bindgrid(); 
    } 
+0

當我使用e.rowIndex時出現此錯誤:(CS1061:'System.Web.UI.WebControls.GridViewDeleteEventArgs'不包含'rowIndex'的定義,並且沒有接受第一個參數類型的擴展方法'rowIndex' ) – azza

+0

它現在的工作,謝謝我只是用e.RowIndex而不是e.rowIndex來避免錯誤 – azza

+0

隨時歡迎! – Sankar

0

的問題是在下面一行

int userid = int.Parse(gridview1.DataKeys[0].Value.ToString()); 

你總是用[0]

獲得第一行的用戶ID

從「e」中獲取適當的值並通過。

e.RowIndex 
0

東西llike這

GridViewRow row = gridview1.Rows[e.RowIndex]; 
int userid = int.Parse(row[0].Value.ToString()); 
0

當前行的索引替換該

int userid = int.Parse(gridview1.DataKeys[e.RowIndex].Value.ToString()); 
+0

我得到這個錯誤:('int.Parse(string)'的最佳重載方法匹配有一些無效參數) – azza