1.数据库中务必设置主键,才可以使用SqlDataSource的高级配置,必须注意在相连的gridview中加
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" OnRowUpdating="GridView1_RowUpdating" DataKeyNames="numID">
为了找出DataKeyNames="numID”这个错误,花费了整整2个小时。终于找到数据修改后为什么没有更新
2.SqlDataSource设置
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:jingluoConnectionString %>" SelectCommand="SELECT [numID], [symptom], [userName], [bodypart] FROM [Symptom] WHERE (([userName] = @userName) AND ([bodypart] = @bodypart))" DeleteCommand="DELETE FROM [Symptom] WHERE [numID] = @numID" InsertCommand="INSERT INTO [Symptom] ([symptom], [userName], [bodypart]) VALUES (@symptom, @userName, @bodypart)" UpdateCommand="UPDATE [Symptom] SET [symptom] = @symptom WHERE [numID] = @numID" > <SelectParameters> <asp:SessionParameter DefaultValue="小明" Name="userName" SessionField="username" Type="String" /> <asp:ControlParameter ControlID="TextBox1" DefaultValue="头部" Name="bodypart" PropertyName="Text" Type="String" /> </SelectParameters> <UpdateParameters> <asp:Parameter Name="symptom" Type="String" /> <asp:Parameter Name="userName" Type="String" /> <asp:Parameter Name="bodypart" Type="String" /> <asp:Parameter Name="numID" Type="Int32" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="numID" Type="Int32" /> </DeleteParameters> <InsertParameters> <asp:Parameter Name="symptom" Type="String" /> <asp:Parameter Name="userName" Type="String" /> <asp:Parameter Name="bodypart" Type="String" /> </InsertParameters> </asp:SqlDataSource>
3.有关在后台修改中的代码
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridView _gridView = (GridView)sender; string key = ""; string value = ""; // NewValues集合里的key string[] _columnKeys = new string[] { "LastName", "FirstName", "Country" }; if (e.RowIndex > -1) { // 循环每一列 //for (int i = _firstEditCellIndex; i < _gridView.Columns.Count; i++) { // 获得单元格里的控件 Control _displayControl = _gridView.Rows[e.RowIndex].Cells[2].Controls[1]; Control _editControl = _gridView.Rows[e.RowIndex].Cells[2].Controls[3]; // 获得列的key key = _columnKeys[2 - _firstEditCellIndex]; // 如果单元格处于编辑模式的话,那么从编辑控件中获取值 if (_editControl.Visible) { if (_editControl is TextBox) { value = ((TextBox)_editControl).Text; } else if (_editControl is DropDownList) { value = ((DropDownList)_editControl).SelectedValue; } // 增加key/value对到NewValues集合 e.NewValues.Add(key, value); } // 否则从显示控件中获取值 else { value = ((Label)_displayControl).Text.ToString(); // 增加key/value对到NewValues集合 e.NewValues.Add(key, value); } } } }