点击&#34后,数据从Repeater中消失;添加行"按键

时间:2017-03-02 19:58:26

标签: c# asp.net

我有一个转发器,可以从参考表中提取数据。转发器上有一个按钮,可以添加一行。该按钮可以很好地添加行,但是,当我在转发器中的新文本框中输入数据并再次单击添加行按钮时,输入到先前添加的行的数据将消失。我需要将数据保留在那些行中按钮添加,我不知所措:

页面加载代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Session["dt2"] = null;
    }
    else
    {
        if (Session["dt2"] == null)
        {
            SqlDataAdapter sda2 = new SqlDataAdapter("select i.reference_id as [Ref ID], r.ref_code as [Ref Code], r.title as Title, r.year as Year, i.pages as [Pages] from item_reference i left join [references] r on r.reference_id = i.reference_id left join item_header h on h.item_header_id = i.item_header_id where h.item_id ='" + cloneItemID.Text + "'", con);
            dt2 = new DataSet();
            sda2.Fill(dt2);
            Session["dt2"] = dt2;
        }
    }

    RptRefs.DataSource = (DataSet)Session["dt2"];
    RptRefs.DataBind();
}

按钮点击代码:

protected void btnRefAddRow_Click(object sender, EventArgs e)
{
    var dt2Data = (DataSet)Session["dt2"];

    for (var i =0; i < RptRefs.Items.Count; i++)
    {
        dt2Data.Tables[0].Rows[i]["Ref ID"] = (RptRefs.Items[i].FindControl("refID") as TextBox).Text;
        dt2Data.Tables[0].Rows[i]["Pages"] = (RptRefs.Items[i].FindControl("Pages") as TextBox).Text;
    }

    var row = dt2Data.Tables[0].NewRow();
    row["Ref ID"] = "0"; 
    row["Ref Code"] = "";
    row["Title"] = "";
    row["Pages"] = "";
    dt2Data.Tables[0].Rows.Add(row);
    Session["dt2"] = dt2Data;
    RptRefs.DataSource = dt2Data;
    RptRefs.DataBind();
}

1 个答案:

答案 0 :(得分:0)

问题是,即使DataSource为真,您也会在Page_Load中设置转发器的IsPostBack。这样,当单击按钮并执行btnRefAddRow_Click之前,将覆盖转发器中更改的数据。

Page_Load为假时,将DataSource更改为仅设置转发器的IsPostBack