我有一个用于FormView(Students)的ObjectDataSource和另一个用于FormView中DropDownList(Name)的ObjectDatSource。如果DropDownList的源不包含与formview的源匹配的名称值,我想显示“不可用”。目前我有这个代码,如果数据源返回NULL值,它可以工作。当FormView名称值不在DropDownList的数据绑定列表中时,如何更改此项以显示“不可用”?
<asp:FormView ID="Students" runat="server" DataSourceID="Students_DataSource">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
</ItemTemplate>
<EditTemplate>
<asp:DropDownList ID="ddlName" runat="server"
SelectedValue='<%# If(Eval("Name") IsNot Nothing, Eval("Name"), "Not Available") %>'
DataSourceID="fvAllNames" runat="server" DataTextField="Name" DataValueField="Name" />
</EditTemplate>
</asp:FormView>
答案 0 :(得分:0)
public class MyItem
{
public string Name { get; set; }
public int UserId { get; set; }
}
public void MethodThatLoadsMyData
{
var originalListData = MethodThatFetchesMyData(45);
myDropDownList.DataSource = MethodThatBumpsTwoItemDatasources(myOuterList, originalListData);
myDropDownList.DataBind();
}
public void MethodThatBumpsTwoItemDatasources(List<MyItem> outerList, List<MyItem> dropdownList)
{
/*This modifies the original result set from the database that you were going
to use to populate your dropdown list. It compares the outer list (whatever that is)
with the result set, and adds items called "Not Available" when there is an item in the
outer list that doesn't exist in the dropdownlist */
var result = new List<Item>();
foreach (var item in listA)
{
var matched = false;
foreach (var itemB in listB.Where(itemB => itemB.Id == item.Id))
{
matched = true;
result.Add(item);
}
if (!matched)
{
result.Add(new Item
{
Name = "Not Available",
Id = 0
});
}
matched = false;
}
return result;
}
public List<MyItem> MethodThatFetchesMyData(int myParameter)
{
//gets my data from the database and builds dto objects
var sql = "my_stored_procedure_or_sql";
var list = new List<MyItems>();
using(var conn = new SqlConnection(myConnectionString))
{
using(var comm = new SqlCommand(sql, conn))
{
//do your normal client setup here (sql type, parameters, etc//
var parameters = SqlParameter[1];
parameters[0] = new SqlParameter("@ParameterName", DbType.Int);
parameters[0].Value = myParameter;
comm.Parameters = parameters;
comm.CommandType = CommandType.StoredProcedure;
conn.Open();
using(var rdr = comm.ExecuteReader())
{
while(rdr.Read())
{
list.Add(
new MyItem{
Name = rdr["NameColumn"].ToString(),
UserId = rdr["ID"]
});
}
return list;
}
}
}
}
在数据绑定控件中,您可以使用典型的
获取itemtemplate中的新值<%#Eval("Name") %> <%#Eval("UserId") %>
我实际上在这里做的是将控件绑定到实际对象列表而不是使用数据源控件构造的数据表。通过这样做,我可以做任何我需要做的事情,然后再将它绑定到控件。在这种情况下,我将两个列表组合在一起,并为那些在一个列表中不存在但在另一个列表中存在的项目添加项目。不确定这是否正是您所需要的,但这应该足以为您提供一些想法。