我有一个填充了多年的列表框并设置了多个选项,但是当发送提交按钮时,值不会延续。我已经研究过,我发现的唯一答案是确保不再重新绑定并在!= postback
中找到它
代码
if (!IsPostBack)
{
CData[] Data = new Conduit().ReadObject(Global.Identifier);
TForm VerifyAct = lClient.GetData(1stId, 2ndid);
ddlPers.DataSource = Enum.GetNames(typeof(PersTaxDocInfoEnum));
ddlPers.DataBind();
ddlCorp.DataSource = Enum.GetNames(typeof(CorpTaxDocInfoEnum));
ddlCorp.DataBind();
var curDate = DateTime.Now.Year;
Int32[] myYears = new Int32[5];
myYears[0] = curDate - 1;
myYears[1] = curDate - 2;
myYears[2] = curDate - 3;
myYears[3] = curDate - 4;
myYears[4] = curDate - 5;
DataTable yearsPast = new DataTable();
yearsPast.Columns.Add("years");
//yearsPast.Rows.Add(myYears);
foreach (Int32 item in myYears)
{
yearsPast.Rows.Add(item);
}
lbYearsDataSource = yearsPast;
lbYearsDataTextField = yearsPast.Columns[0].ToString();
lbYearsDataValueField = yearsPast.Columns[0].ToString();
lbYears.DataBind();
ddlCorp.Visible = false;
ddlPers.Visible = false;
lbYears.Visible = false;
btnSubmit.Enabled = false;
}
}
实际代码
int i = 0;
foreach (ListItem item in lbYears.Items)
{
if (item.Selected)
{
fooYears[0] = item.Text;
}
}
if (ddltype.SelectedValue=="2")
{
taxForm = ddlPers.SelectedValue.ToString();
}
else
{
Form = ddlCorp.SelectedValue.ToString();
}
这会出现一个null异常。我和可能永远都是开发的新手,但我已经使用Visual Studio进行调试,并且没有遇到值,我无法弄明白。任何帮助将不胜感激
答案 0 :(得分:0)
您可以通过多种方式将数据填充到 ListBox 。但是,创建表只是为了将项目分配给 ListBox 有点奇怪。
您可以查看以下示例 -
<asp:ListBox ID="YearListBox" runat="server"
SelectionMode="Multiple" />
<asp:Button runat="server" ID="SubmitButton"
OnClick="SubmitButton_Click" Text="Submit" />
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int year = DateTime.Now.Year;
for (int i = 0; i < 5; i ++)
{
string item = (year - i).ToString();
YearListBox.Items.Add(new ListItem(item, item));
}
}
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
IList<string> selectedValues = YearListBox.Items.Cast<ListItem>()
.Where(x => x.Selected)
.Select(x => x.Value)
.ToList();
}