我有一个GridView
,它绑定到一个数据库。我在更新GridView
数据库中的相应表时发现困难。
GridView
我绑定到 SQLdatasource 后的 asp 代码是:
<asp:GridView ID="GridView2" runat="server" OnRowEditing="GridView2_RowEditing"
OnRowUpdating="GridView2_RowUpdating" CellPadding="4" ForeColor="#333333" OnRowCancelingEdit="GridView2_RowCancelingEdit"
OnRowDataBound="GridView2_RowDataBound" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" AutoGenerateEditButton="True" DataKeyNames="Locations">
<Columns>
<asp:BoundField DataField="Locations" HeaderText="Locations"
SortExpression="Locations" ReadOnly="true"/>
<asp:BoundField DataField="Lamp_pro4" HeaderText="Lamp_pro4"
SortExpression="Lamp_pro4" />
<asp:BoundField DataField="Lamp_pro5" HeaderText="Lamp_pro5"
SortExpression="Lamp_pro5" />
<asp:BoundField DataField="AC_Profile5" HeaderText="AC_Profile5"
SortExpression="AC_Profile5" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TouchPadConnectionString %>"
SelectCommand="SELECT * FROM [Quantity]">
</asp:SqlDataSource>
我的数据键是 Locations 并且它是只读的。
用于更新的 .cs 代码是:
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=ARCHANA-PC\\ARCHANA;Initial Catalog=TouchPad;Integrated Security=True");
string LocName = GridView2.DataKeys[e.RowIndex].Values["Locations"].ToString();
TextBox txt1 = (TextBox)GridView2.Rows[e.RowIndex].FindControl("Lamp_pro4");
TextBox txt2 = (TextBox)GridView2.Rows[e.RowIndex].FindControl("Lamp_pro5");
TextBox txt3 = (TextBox)GridView2.Rows[e.RowIndex].FindControl("AC_Profile5");
string updStmt = "UPDATE Quantity set Lamp_pro4=@Lamp_pro4,Lamp_pro5=@Lamp_pro5,AC_Profile5=@AC_Profile5 where Locations=@locName";
con.Open();
SqlCommand updCmd = new SqlCommand(updStmt, con);
updCmd.Parameters.AddWithValue("@locName", LocName);
updCmd.Parameters.AddWithValue("@Lamp_pro4", txt1.Text);
updCmd.Parameters.AddWithValue("@Lamp_pro5", txt2.Text);
updCmd.Parameters.AddWithValue("@AC_Profile5", txt3.Text);
updCmd.ExecuteNonQuery();
GridView2.DataBind();
}