我正在尝试创建一个语言选择器 我将此代码用于下拉列表
<asp:DropDownList ID="ddlGender" runat="server" Width="200px">
<asp:ListItem Text="Select Language"></asp:ListItem>
<asp:ListItem Text="English" ></asp:ListItem>
<asp:ListItem Text="Albanian" ></asp:ListItem>
</asp:DropDownList>
但是,现在我想将Country图标放在那些2.我的项目中的Images文件夹中有2个图像。例如Images / EnglishFlag.png 我怎样才能将它们放入下拉列表中?
我看到很多视频或代码都是这样做的,但他们从SQL数据库中获取了图像。
有什么建议吗?
答案 0 :(得分:2)
使用以下内容:
Default.aspx的:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px">
</asp:DropDownList>
</div>
</form>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable objdt = new DataTable();
objdt = GetData();
DropDownList1.DataSource = objdt;
DropDownList1.DataTextField = "Country";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();
string imageURL = "";
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
switch (DropDownList1.Items[i].Text)
{
case "Bangladesh": imageURL = "Images/flag-of-Bangladesh.png";
break;
case "China": imageURL = "Images/flag-of-China.png";
break;
case "Germany": imageURL = "Images/flag-of-Germany.png";
break;
case "USA": imageURL = "Images/flag-of-USA.png";
break;
}
ListItem item = DropDownList1.Items[i];
item.Attributes["style"] = "background: url(" + imageURL + ");background-repeat:no-repeat;";
}
}
}
public DataTable GetData()
{
DataTable _objdt = new DataTable();
_objdt.Columns.Add("Country", typeof(string));
_objdt.Columns.Add("Id", typeof(long));
_objdt.Columns.Add("LabelValue");
var _objrow = _objdt.NewRow();
_objrow["Country"] = "Bangladesh";
_objrow["Id"] = 1;
_objdt.Rows.Add(_objrow);
_objrow = _objdt.NewRow();
_objrow["Country"] = "China";
_objrow["Id"] = 2;
_objdt.Rows.Add(_objrow);
_objrow = _objdt.NewRow();
_objrow["Country"] = "Germany";
_objrow["Id"] = 3;
_objdt.Rows.Add(_objrow);
_objrow = _objdt.NewRow();
_objrow["Country"] = "USA";
_objrow["Id"] = 4;
_objdt.Rows.Add(_objrow);
return _objdt;
}