3

我一直在努力处理 ASP .NET / C# 中 GridView 中的 CheckBox 列。完成后,此页面应显示我办公室的当前空缺职位。人们应该能够检查他们想申请的尽可能多的职位,然后继续到下一个屏幕(实际申请开始的地方)。

这是单击“立即应用”按钮时我运行的例程。在尝试了我的老板和这里的人建议的十几种其他组合后,我在这里找到了这段代码。当我运行它时,isChecked = false,因此它不会在该 if 语句中运行任何内容。我错过了一些明显的东西吗?

for (int i = GridView1.Rows.Count - 1; i > -1; i--)
{
    GridViewRow row = GridView1.Rows[i];
    bool isChecked = ((CheckBox)row.FindControl("cbx_apply")).Checked;

    if (isChecked)
    {
        try
        {
            Response.Write("Hello world");
            PositionsAppliedFor.Add(Convert.ToInt32((GridView1.Rows[i].Cells[1].Text)));
            Session["SelectedPositionIDList"] = PositionsAppliedFor;
        }
        catch (Exception error)
        {
            Response.Write(error.Message);
        }
    }
}

编辑:另外,我意识到我在 if 语句中所做的事情并不重要。我只是想让它做 /something/。

ASP.NET:

<asp:GridView ID="GridView1" runat="server" 
              onselectedindexchanged="UpdateSelectedPostions">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="cbx_apply" runat="server" 
                              OnCheckedChanged="UpdateSelectedPostions"
                              AutoPostBack="false"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

很简单,而且可能遗漏了很多。我是/非常/ ASP.NET 的新手。

这是我为网格加载数据并绑定它的地方:

string sqlstatement = "SELECT * FROM dbo.POSITION WHERE PositionStartDate < GETDATE() AND PositionEndDate > GETDATE()";
command = new SqlCommand(sqlstatement, connection);
ds = new DataSet();
adapter = new SqlDataAdapter(command);
builder = new SqlCommandBuilder(adapter);
adapter.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
connection.Close();

希望这已经足够了,因为它真的是我所拥有的。我还没有在页面上放任何其他东西——只是想让这些愚蠢的复选框同意我的观点。

4

2 回答 2

8

确保您的绑定代码位于这样的块中:

if (!Page.IsPostBack)
{

}

否则,您将在每次回发时重新创建复选框,从而失去它们已被选中的事实。

于 2012-06-26T14:21:44.150 回答
5

如果你的代码

string sqlstatement = "SELECT * FROM dbo.POSITION WHERE PositionStartDate < GETDATE() AND PositionEndDate > GETDATE()";
command = new SqlCommand(sqlstatement, connection);
ds = new DataSet();
adapter = new SqlDataAdapter(command);
builder = new SqlCommandBuilder(adapter);
adapter.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
connection.Close();

在 page_load 方法中,每次您回帖时都会调用它,您应该阅读内容,这将使您对此有更好的理解。

为避免每次回发时都运行此代码

if(!Page.IsPostBack)
{

}

另外在旁注中,您正在调用 CheckChanged 和 SelectedIndexChanged 上的 UpdateSelectedPostions 您是否打算这样做?

于 2012-06-26T14:21:36.783 回答