我有一个包含标签和下拉列表的ListView。我想通过使用下拉列表的SelectMethod属性中的FindControl()
找到标签。这是我的代码:
的.aspx:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID"
ItemType="Models.Items" SelectMethod="GetItem">
<ItemTemplate>
<asp:Label ID="LabelItemId" runat="server"
Text="<%#: Item.ID %>"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server"
SelectMethod="GetCategories" ItemType="Models.Category"
DataValueField="CategoryID" DataTextField="CategoryName">
</asp:DropDownList>
C#:
protected void GetCategories(object sender, ListViewItemEventArgs e)
{
using (var db = new ItemContext())
{
var dropDownList = (DropDownList)e.Item.FindControl("DropDownList1");
IQueryable<Category> query = db.Categories;
List<Category> categories = query.ToList();
//The line below is the problem because e is null
var item = categories.First(category => category.CategoryID ==
Convert.ToInt32(((Label)e.Item.FindControl("LabelItemId")).Text));
}
}
问题是e
的{{1}}为空。所以,我得到了ListViewItemEventArgs
。也许原因是我不应该将NullReferenceException
用于ListViewItemEventArgs
属性。如果是这样的话,我该怎么用?
答案 0 :(得分:1)
您需要迭代循环以获取标签值,如下所示:
foreach (ListViewItem item in ListView1.Items)
{
Label mylabel = (Label)item.FindControl("Label1");
lblID.Text = mylabel.Text;
}
注意:这也适用于其他控件。
如果它不起作用,还有另一种解决方案。执行以下操作:
ListViewItem item = ListView1.Items[ListView1.SelectedIndex];
Label myLabel = (Label)item.FindControl("Label1");
string result = myLabel.text; //Get the text here
答案 1 :(得分:0)
只需将public void AddNewUser()
{
Window2 window = new Window2();
if (window.ShowDialog() == true)
{
// Update DataGrid
RefreshDataGrid();
}
}
属性添加到OnDataBound
,然后为DropDownList
事件编写此方法:
<强> C#:强>
OnDataBound
这会根据 protected void DropDownList1_DataBound(object sender, EventArgs e)
{
var control = (Control)sender;
var lvi = (ListViewItem)control.NamingContainer;
var label = (Label)lvi.FindControl("LabelCategoryId");
string text = label.Text;
var ddl = (DropDownList)sender;
ddl.SelectedValue = text;
}
中每个项目的标签文字更改SelectedValue
的{{1}}。