页面加载的数据库记录 - 动态文本字段

时间:2015-10-30 15:34:07

标签: c# asp.net

我正在使用动态创建的文本字段。到目前为止我发现的大多数解决方案都与保留视图状态有关,但我相信我已经解决了这个问题。在回发时,将保留文本字段中的值。

我遇到的问题:我无法获取当前存储的数据库值以加载到动态字段中。我目前正在调用loadUpdates()来尝试这样做,但不确定如何获取数据行,同时还要确保我可以继续添加新字段(或删除它们)。我怎样才能做到这一点?

" txtProjectsUpdate"是文本字段," hidFKID"是父表的外键," hidUpdateID"是子表中主键的隐藏值(我尝试加载的值)。

标记:

<div>
    <asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
    <asp:Placeholder ID="placeHolderControls" runat="server"/>
</div>

<asp:TextBox runat = "server" ID = "hidUpdateID" />
<asp:HiddenField runat = "server" ID = "hidFKID" />

代码背后:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            for (var i = 0; i < TextBoxCount; i++)
                AddTextBox(i);
        }

        if (!IsPostBack)
        {

            DataTable dt = new DataTable();
            dt = selectDetails();
            tryHidFKID(hidFKID, dt.Rows[0]["fkprjNumber"].ToString());


            loadUpdates();
        }
    }

protected void btnAddTextBox_Click(object sender, EventArgs e)
    {
        AddTextBox(TextBoxCount);
        TextBoxCount++;
    }

    private int TextBoxCount
    {
        get
        {
            var count = ViewState["txtBoxCount"];
            return (count == null) ? 0 : (int)count;
        }
        set { ViewState["txtBoxCount"] = value; }
    }

    private void btnRemove_Click(object sender, EventArgs e)
    {
        var btnRemove = sender as Button;
        if (btnRemove == null) return;
        btnRemove.Parent.Visible = false;
    }

    private void AddTextBox(int index)
    {
        var panel = new Panel();
        panel.Controls.Add(new TextBox
        {
            ID = string.Concat("txtProjectUpdates", index),
            Rows = 5,
            Columns = 130,
            TextMode = TextBoxMode.MultiLine,
            CssClass = "form-control",
            MaxLength = 500
        });

        panel.Controls.Add(new TextBox
        {
            ID = string.Concat("hidUpdateID", index)
        });

        var btn = new Button { Text = "Remove" };
        btn.Click += btnRemove_Click;
        panel.Controls.Add(btn);
        placeHolderControls.Controls.Add(panel);
    }

protected void loadUpdates()
    {
        DataTable dt = dbClass.ExecuteDataTable
        (
            "spSelectRecords", <db>, new SqlParameter[1]
            {
                new SqlParameter ("@vFKPrjNumber", hidFKID.Value)
            }
        );
            AddTextBox(TextBoxCount);
            TextBoxCount++;
    }
protected void tryHidFKID(HiddenField hidFKID, string txtSelected)
    {
        try
        {
            hidFKID.Value = txtSelected;
        }
        catch
        {
            hidFKID.Value = "";
        }
    }

0 个答案:

没有答案