我在处理更新gridview的功能时遇到问题。到目前为止,我一直在使用DataSource控件,但这次我需要从头开始构建所有内容。我希望能够只更新gridview的最后一个数据列。我的问题是: 1)当我单击编辑按钮时,行中的所有数据字段都会转换为文本框 - 我只想最后一个这样做 2)当我点击更新时,我得到“对象引用未设置为对象的实例”。错误,似乎“TextBox tProgress =(TextBox)grdMilestones.Rows [e.RowIndex] .Cells [3] .FindControl(”mstCompletition“);”只是找不到正确的值,因为当我用数字替换它时,它可以正常工作。
这是我的gridview
<asp:GridView ID="grdMilestones" runat="server" Width="940px" DataKeyNames="mstNo"
OnRowEditing="grdMilestones_RowEditing"
OnRowCancelingEdit="grdMilestones_RowCancelingEdit"
OnRowUpdating="grdMilestones_RowUpdating" AutoGenerateColumns="False"
CssClass="milestonesGrid">
<Columns>
<asp:BoundField DataField="proName" HeaderText="Project Name" />
<asp:BoundField DataField="mstDescription" HeaderText="Milestone Description" />
<asp:BoundField DataField="mstPersResp" HeaderText="Milestone Leader" />
<asp:BoundField DataField="mstCompletition" HeaderText="Progress" DataFormatString{0:F1}%" />
<asp:CommandField ButtonType="Button" ShowEditButton="true" EditText="Update progress" />
</Columns>
</asp:GridView>
背后的代码
protected void grdMilestones_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = Int32.Parse(grdMilestones.DataKeys[e.RowIndex].Value.ToString());
TextBox tProgress = (TextBox)grdMilestones.Rows[e.RowIndex].Cells[3].FindControl("mstCompletition");
int prog = Convert.ToInt32(tProgress.Text.Trim());
//ds.Rows[row.DataItemIndex]["mstCompletition"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
string updateSQL = "UPDATE milestonesPM SET mstCompletition = @mstCompletition WHERE mstNo = @mstNo";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(updateSQL, con);
cmd.Parameters.Add("@mstNo", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@mstCompletition", SqlDbType.SmallInt).Value = prog;
con.Open();
cmd.ExecuteNonQuery();
grdMilestones.EditIndex = -1;
grdMilestones.DataBind();
con.Close();
fillGrid();
}
此致
的Bartosz
答案 0 :(得分:0)
您需要将您不想编辑的列设为只读,并为要编辑的列创建EditItemTemplate
:
<asp:BoundField DataField="proName"
ReadOnly="true"
HeaderText="Project Name" />
<asp:TemplateField HeaderText="Progress">
<ItemTemplate>
<asp:Label ID="mstCompletitionLabel" Text='<%# Eval("Description") %>'
runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="mstCompletitionTextBox" CssClass="textBox"
runat="server"
TabIndex="12"
Width="175"
Text='<%# Eval("mstCompletition") %>'
MaxLength="20">
</asp:TextBox>
<asp:RequiredFieldValidator ID="mstCompletitionValidator"
runat="server"
ErrorMessage="Required"
Text="*"
ControlToValidate="mstCompletitionTextBox"
SetFocusOnError="true"
Display="Static">
</asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>