2011-12-13 51 views
1

我正在使用asp.net網格視圖從我的sql數據表中加載數據。我能夠成功加載數據。asp.net網格視圖批量更新所有單元格

SQL表DESGIN: 3 cloumns:位置,名字,姓氏

位置是主鍵。

設計:

Aspxpage具有有兩個按鈕在底部一個GridView:

  1. 編輯
  2. 保存

當用戶點擊編輯按鈕,所有的細胞在GridView都是可編輯的,以便用戶可以編輯和保存這些值。

我的問題出現在保存按鈕,我無法將編輯的數據保存回SQL。

這裏是保存按鈕,單擊該代碼:

protected void btnSave_Click(object sender, EventArgs e) 
{ 
    int RowIndex=0; 

    GridViewRow row = (GridViewRow)gvres.Rows[RowIndex]; 

    TextBox txtLanguage1 = row.FindControl("txtFName") as TextBox; 
    TextBox txtLanguage2 = row.FindControl("txtLName") as TextBox; 

    SqlConnection myConnection = new SqlConnection(connectionString); 
    SqlCommand cmd = new SqlCommand("UPDATE UsersTable SET FirstName = @FirstName, LastName = @LastName WHERE Location = @Location", myConnection); 


    cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim()); 
    cmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim()); 

    myConnection.Open(); 
    cmd.ExecuteNonQuery(); 
    gvusers.EditIndex = -1; 
    DataBind(); 
} 

例外: 「必須聲明標量變量 」@location「。」

+0

@Location表示插入/更新需要將該字段傳入/添加到您的cmd.Parameters中,您將添加@Location ...?看看你有這個WHERE Location的位置= @Location「,myConnection); add/declare cmd.Parameters.AddWithValue(」@ Location「,someLocationValue.Trim()); – MethodMan

+0

RowIndex變量被硬編碼爲0,所以只有第一行將被更新如果整個網格只有一個保存按鈕,那將是一個問題 –

+0

是啊,這就是我現在發現的。它只是upadating第一行..所以我怎麼循環所有的行並更新。 – Macnique

回答

3

您需要將一個參數添加到名爲「@Location」的SqlCommand對象。您提到位置是網格中的一列 - 您可以從列中讀取值(類似於獲取名字和姓氏的方式),也可以將「位置」指定爲數據鍵,並從網格的DataKeys屬性中獲取它。

我想看看Codeplex上的ASP.NET Real World Controls項目。它允許批量編輯,並且足夠智能,只更新已更改的行。

+0

這非常有幫助。 – Macnique

2
//@Location means that the Insert/Update expects that field to be passed in/added //to your cmd.Parameters where are you adding @Location...? 

//看,你有這其中location = @location行」,MyConnection的); // 宣佈加cmd.Parameters.AddWithValue( 「@位置」,someLocationValue.Trim());

2
protected void btnSave_Click(object sender, EventArgs e) 
{ 
    int RowIndex=0; 

    GridViewRow row = (GridViewRow)gvres.Rows[RowIndex]; 

    TextBox txtLanguage1 = row.FindControl("txtFName") as TextBox; 
    TextBox txtLanguage2 = row.FindControl("txtLName") as TextBox; 
    TextBox txtLanguage3 = row.FindControl("txtLocation") as TextBox; 


    SqlConnection myConnection = new SqlConnection(connectionString); 
    SqlCommand cmd = new SqlCommand("UPDATE UsersTable SET FirstName = @FirstName, LastName = @LastName WHERE Location = @Location", myConnection); 

cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text.Trim()); 
cmd.Parameters.AddWithValue("@LastName", txtLastName.Text.Trim()); 

cmd.Parameters.AddWithValue( 「@位置」,txtLocation.Text.Trim());

myConnection.Open(); 
cmd.ExecuteNonQuery(); 
gvusers.EditIndex = -1; 
DataBind(); 

}