我创建了一个数据表globaly,我在页面加载事件中添加了列。 现在我想在按钮点击事件中添加数据。 当我这样做时,我得到一个错误说....
列'catID'不属于表
解决方案是什么......我需要使用会话......?代码如下所示
public partial class Default2 : System.Web.UI.Page
{
DataTable dtSelectedSeats = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dtSelectedSeats.Columns.Add("catID", typeof(string));
dtSelectedSeats.Columns.Add("seatID", typeof(string));
}
}
protected void seat_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (button.BackColor == Color.Cyan)
{
button.BackColor = Color.Lime;
addSeat(button.Text);
}
}
private void addSeat(string seatNo)
{
DataRow dr;
dr = dtSelectedSeats.NewRow();
dr["catID"] = ddlCategory.SelectedItem.Value.ToString();
dr["seatID"] = seatNo;
dtSelectedSeats.Rows.Add(dr);
}
}
答案 0 :(得分:1)
ASPX:
<asp:DropDownList ID="ddlCategory" runat="server">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="seat" runat="server" BackColor="Cyan" onclick="seat_Click" Text="1" />
<asp:Button ID="Button1" runat="server" BackColor="Cyan" onclick="Button1_Click" Text="2" />
<asp:Button ID="Button2" runat="server" BackColor="Cyan" onclick="Button2_Click" Text="3" /><br />
<asp:GridView ID="GridView1" runat="server"/>
代码背后:
protected void seat_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (button.BackColor == Color.Cyan)
{
button.BackColor = Color.Lime;
addSeat(button.Text);
}
}
private void addSeat(string seatNo)
{
if (Session["dt"] == null)
{
Response.Write("DataTable not exist!");
return;
}
DataTable dtSelectedSeats = (DataTable)Session["dt"];
DataRow dr = dtSelectedSeats.NewRow();
dr["catID"] = ddlCategory.SelectedItem.Value.ToString();
dr["seatID"] = seatNo;
dtSelectedSeats.Rows.Add(dr);
GridView1.DataSource = dtSelectedSeats;
GridView1.DataBind();
Session["dt"] = dtSelectedSeats;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtSelectedSeats = new DataTable();
dtSelectedSeats.Columns.Add("catID", typeof(string));
dtSelectedSeats.Columns.Add("seatID", typeof(string));
Session["dt"] = dtSelectedSeats;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
seat_Click(sender, e);
}
protected void Button2_Click(object sender, EventArgs e)
{
seat_Click(sender, e);
}
答案 1 :(得分:0)
删除if (!IsPostBack)
当你点击按钮时,页面会回发。
答案 2 :(得分:0)
您的代码对DataTable完全正确,您获得的错误可能是针对某些不同的问题。请正确指出您的错误
答案 3 :(得分:0)
就在我的脑海中,看起来好像是在错误的事件中添加行。我不确定您的DataTable是否已在向其添加列时初始化(因此丢弃了您的更改)。尝试将您的PageLoad代码放入PagePrerender,看看是否能给您带来更好的结果。