我有这段代码
protected void btnPrasaj_Click(object sender, EventArgs e)
{
List<ListItem> lista = new List<ListItem>();
string prasanje = null;
Application.Lock();
if (Application["prasanja"] == null) // za prvpat se postavuva prasanje
{
prasanje = txtNaslov.Text + "\n\n\n" + txtPrasanje.Text;
lista.Add(new ListItem(prasanje, ddltema.SelectedIndex.ToString()));
lstProblemPrasanje.DataSource = lista;
lstProblemPrasanje.DataTextField = "Text";
lstProblemPrasanje.DataValueField = "Value";
lstProblemPrasanje.DataBind();
Application["prasanja"] = lista;
}
else
{
lista=(List<ListItem>)Application["prasanja"];
prasanje = txtNaslov.Text + "\n\n\n" + txtPrasanje.Text;
lista.Add(new ListItem(prasanje, ddltema.SelectedIndex.ToString()));
lstProblemPrasanje.DataSource = lista;
lstProblemPrasanje.DataTextField = "Text";
lstProblemPrasanje.DataValueField = "Value";
lstProblemPrasanje.DataBind();
Application["prasanja"] = lista;
}
Application.UnLock();
}
当我在ListBox中单击此按钮时,我得到数字(这是项目的值)而不是文本字段的内容。
答案 0 :(得分:2)
由于您的数据源是ListItems的List,因此您不必指定DataTextField和DataValueField。只需注释掉以下几行。
lstProblemPrasanje.DataTextField = "Text";
lstProblemPrasanje.DataValueField = "Value";
所以你的代码应该是:
protected void btnPrasaj_Click(object sender, EventArgs e)
{
List<ListItem> lista = new List<ListItem>();
string prasanje = null;
Application.Lock();
if (Application["prasanja"] == null) // za prvpat se postavuva prasanje
{
prasanje = txtNaslov.Text + "\n\n\n" + txtPrasanje.Text;
lista.Add(new ListItem(prasanje, ddltema.SelectedIndex.ToString()));
lstProblemPrasanje.DataSource = lista;
//lstProblemPrasanje.DataTextField = "Text";
//lstProblemPrasanje.DataValueField = "Value";
lstProblemPrasanje.DataBind();
Application["prasanja"] = lista;
}
else
{
lista=(List<ListItem>)Application["prasanja"];
prasanje = txtNaslov.Text + "\n\n\n" + txtPrasanje.Text;
lista.Add(new ListItem(prasanje, ddltema.SelectedIndex.ToString()));
lstProblemPrasanje.DataSource = lista;
//lstProblemPrasanje.DataTextField = "Text";
//lstProblemPrasanje.DataValueField = "Value";
lstProblemPrasanje.DataBind();
Application["prasanja"] = lista;
}
Application.UnLock();
}
答案 1 :(得分:2)
如果是这样的数据源项,您不需要明确指定DataText
和DataValue
字段,也可以通过以下方式删除if/else
中的重复部分来简化代码:
protected void btnPrasaj_Click(object sender, EventArgs e)
{
string key = "prasanja";
List<ListItem> lista = new List<ListItem>();
string prasanje = null;
Application.Lock();
if (Application[key] != null) // za prvpat se postavuva prasanje
{
lista = (List<ListItem>)Application[key];
}
prasanje = txtNaslov.Text + "\n\n\n" + txtPrasanje.Text;
lista.Add(new ListItem(prasanje, ddltema.SelectedIndex.ToString()));
lstProblemPrasanje.DataSource = lista;
lstProblemPrasanje.DataBind();
Application[key] = lista;
Application.UnLock();
}