c# - 在 RowCommand 上填充 DDL
问题描述
我有一个带有 arowcommand
和 a的网格视图linkbutton
。当我按下链接按钮时,行被编辑但是 DDL 应该将数据与我的数据库表中的值绑定,但这不起作用
我不知道这是否是正确的方法,但是在按下链接按钮“对象引用未设置为对象的实例”时确实出现错误。但我不认为这是这里的主要问题。
从 Rowcommand 编辑时我应该绑定我的 DDL 行还是有人能看到我做错了什么?
DDL 列的 ASPX 标记:
<asp:TemplateField HeaderText="Status">
<EditItemTemplate>
<asp:DropDownList ID="ddlStatusRow" AppendDataBoundItems="True" runat="server" >
<asp:ListItem>Status</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfEditStatus" runat="server" ErrorMessage ="Status is a required field"
ControlToValidate="ddlStatusRow" Text="*" ForColor="Red" InitialValue="Status">
</asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle BackColor="#E6E6E6" Font-Bold="False" Font-Names="Arial" Font-Size="14px" ForeColor="Black" />
<ItemStyle Font-Size="12px" HorizontalAlign="Center" Width="4%" />
</asp:TemplateField>
代码隐藏:
protected void gwUnplannedActivities_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
gwUnplannedActivities.EditIndex = rowIndex;
BindGridViewUnplannedActivities();
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
DropDownList ddlStatusRow = (DropDownList)row.Cells[3].FindControl("ddlStatusRow");
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM ....", con);
con.Open();
ddlStatusRow.DataSource = cmd.ExecuteReader();
ddlStatusRow.DataTextField = "Status";
ddlStatusRow.DataBind();
}
}
else if (e.CommandName == "CancelUpdate")
{
//somecode....
}
else if (e.CommandName == "UpdateRow")
{
//somecode....
}
}
解决方案
用这个
GridView gv = (GridView)sender;
DropDownList ddlStatusRow = (DropDownList)gv.Rows[rowIndex].FindControl("ddlStatusRow");
代替
GridViewRow row = ((e.CommandSource as Control).NamingContainer as GridViewRow);
DropDownList ddlStatusRow = (DropDownList)row.Cells[3].FindControl("ddlStatusRow");
问题是已经设置了编辑索引,因此row
不再退出,因为它已被可编辑行替换。
推荐阅读
- jquery - 第二次验证失败时未显示工具提示
- php - 如何使用 API 响应验证用户并登录他?
- elasticsearch - ES , Group By field ORDER by date
- javascript - 选择下拉列表时如何自动填充文本框
- swift - 从 coreData 与 Array.sort 检索时使用 sortDescriptors 是否存在性能差异?
- javascript - 仅当满足条件时才在 'fetch' 中执行 'then'
- resources - 是否存在对角线移动的资源?
- r - 如何将文件夹中的所有 JPEG 图像加载到 R 变量?
- selenium - 使用 selenium 提取网站的面包屑
- java - 如何在java中从一个线程运行多个get请求?