【发布时间】:2015-07-15 18:50:24
【问题描述】:
我正在尝试在我的 GridView 中将某些列设置为只读。由于我对几个不同的视图使用相同的 ASPX,因此我需要在后端代码中执行此操作。我已经看过几篇关于此的帖子,但不确定我做错了什么。我收到错误 Object reference not set to an instance of an object.
这是我的代码:
protected void FormsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = (DataBinder.Eval(e.Row.DataItem, "ID")) as TextBox;
txt.ReadOnly = true;
}
}
我也尝试了以下相同的结果。
TextBox txt = (TextBox)e.Row.FindControl("ID");
txt.ReadOnly = true;
我也尝试了以下并得到错误Index was out of range. Must be non-negative and less than the size of the collection.
((BoundField)FormsGridView.Columns[1]).ReadOnly = true;
我做错了什么?
编辑:添加了 GridView 代码
<asp:GridView ID="FormsGridView" runat="server"
DataSourceID="SqlDS1" OnDataBound="FormsGridView_DataBound" AllowPaging="True"
AllowSorting="True" PageSize="1000" onprerender="GridView_PreRender"
CssClass="GridView" onrowcreated="FormsGridView_RowDataBound">
<PagerSettings Position="Top" />
<Columns>
<asp:TemplateField ItemStyle-Wrap="False">
<ItemTemplate>
<asp:HyperLink ID="DeleteButton" runat="server">
<img src="images/delete.png" alt="Delete Item" width="16px" height="16px" style="cursor:pointer;vertical-align:bottom;text-decoration:none" /></asp:HyperLink>
<asp:HyperLink ID="EditButton" runat="server">
<img src="images/edit.png" alt="Edit Item" width="16px" height="16px" style="cursor:pointer;vertical-align:bottom;text-decoration:none" /></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate>
<div class="pages">
<asp:DropDownList ID="PagingDropDownList" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="PagingDropDownList_SelectedIndexChanged" height="30px" />
</div>
</PagerTemplate>
</asp:GridView>
UpdateCommand 也在后端完成:
FormsGridView.AutoGenerateEditButton = true;
SqlDS1.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure;
SqlDS1.UpdateCommand = ("SP");
我觉得奇怪的是,我可以使用以下方法从单元格中提取值:
id = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "ID"));
但是当我尝试作为 TextBox 引用时,我得到了 Object reference not set to an instance of an object. 错误。
TextBox txt = (DataBinder.Eval(e.Row.DataItem, "ID")) as TextBox;
txt.ReadOnly = true;
只是为了好玩,我将名称“ID”更改为存储过程不返回的“SomeID”,实际上我确实得到了一个与预期不同的错误DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'SomeID'.
【问题讨论】:
-
请发布您的 GridView 标记。
-
根据您的错误,显然没有找到您的控件
Id。您的语法看起来有效,但我们需要查看您的 Grid 语法。 -
@Greg 按要求添加了 GridView
-
@doby48 你的
Id控件/文本框在哪里,我在你的代码中看不到它。 -
@Greg 我的 ASPX 中没有文本框,我正在使用 AutoGenerateColumns,这看起来是这里的问题。我找到了一个解决方案,采用不同的方式将某些列设置为 ReadOnly,并将其添加为下面的答案。