动态地将itemplate添加到gridview

时间:2017-06-01 05:42:32

标签: c# asp.net gridview

我创建了gridview。添加了一个文本框,用于指定用户想要动态添加到网格中的列数,并成功完成。

我想在动态添加的字段中添加文本框以输入数据并将其保存到数据库中(我可以向行添加文本字段并保存数据)但我还没有得到任何解决方案。

我尝试过使用itemplate,但我对此并不了解。我在下面添加了我的代码。 这是我的aspx代码

                                                                                                                                                                                                                                                                             

                        <input type="hidden" runat="server" value="0" id="columnAdded"/>
                    </td>
                </tr>
                <tr>
                    <td>

                    </td>
                </tr>
            </table>




<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <%--<asp:CommandField ShowEditButton="True" />--%>

        <asp:TemplateField HeaderText="S. No.">
            <ItemTemplate>
                <asp:Label ID="lblsno"  runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
            </FooterTemplate>
        </asp:TemplateField>


           <asp:BoundField HeaderText="Parts" DataField="parts">

            </asp:BoundField>

         <%--<asp:TemplateField>
            <ItemTemplate>
                <asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
            </ItemTemplate>

        </asp:TemplateField>--%>

        <%--<asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
            </ItemTemplate>
        </asp:TemplateField>--%>

        </Columns>
</asp:GridView>

这里是.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        try
        {
            drpstation.Items.Clear();

            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
            cmd.ExecuteNonQuery();
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds, "stationdesc");

            drpstation.DataSource = ds.Tables[0];
            drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
            drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
            drpstation.DataBind();
            drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
        }
        catch (Exception ex)
        {
            string Msg = "select station error";
            Msg += ex.Message;
        }
        finally
        {
            con.Close();
        }
    }
    if (!IsPostBack)
    {

        griddisplay();


    }
}
public void griddisplay()
{
    try
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
        SqlDataReader dr = cmd.ExecuteReader();
        GridView1.DataSource = dr;
        GridView1.DataBind();
        //DataTable dt = new DataTable();
        //dt.Columns.Add("Parts", typeof(string));
        //DataRow drr = dt.NewRow();
        //drr["Parts"] = "Weldmet";
        //dt.Rows.Add(drr);

        //drr = dt.NewRow();
        //drr["Parts"] = "MFG Parts";
        //dt.Rows.Add(drr);

        //GridView1.DataSource = dt;
        //GridView1.DataBind();

    }
    catch (Exception d)
    {
        string message = "grid error";
        message += d.Message;
    }
    finally
    {
        con.Close();
    }
}
protected void btnadd_Click(object sender, EventArgs e)
{
    int num;
    num = Convert.ToInt32(txtnumber.Text.Trim());
    int addedColumn = Convert.ToInt32(columnAdded.Value);
    for (int i = addedColumn + 1; i <= addedColumn + num; i++)
    {
        string name = "Unit";
        name = string.Concat(name, i);
        TemplateField test = new TemplateField();
        test.HeaderText = name;
        GridView1.Columns.Add(test);
        TextBox txtname = new TextBox();
        string txtunit = "txtunit";
        txtname.ID = txtunit + i;

    }
    griddisplay();
    columnAdded.Value = (addedColumn + num).ToString();
}

public class TemplateHandler : ITemplate
{


    void ITemplate.InstantiateIn(Control container)
    {
        TextBox txtbox = new TextBox();

        txtbox.Text = "test";
        txtbox.DataBinding += Txtbox_Binding;
        container.Controls.Add(txtbox);

    }

    private void Txtbox_Binding(object sender, EventArgs e)
    {
        //throw new NotImplementedException();
        TextBox txttest = (TextBox)sender;
        GridViewRow container = (GridViewRow)txttest.NamingContainer;
        //txttest.Text = ((TableNameClass)container.DataItem).SkillText;
        ((DataRowView)container.DataItem)["SkillText"].ToString();
    }
}

请帮忙

1 个答案:

答案 0 :(得分:0)

根据您发布的代码,只是一个伪/示例代码(未经过测试!),为您提供一些提示

protected void btnadd_Click(object sender, EventArgs e)
{
    int num;
    num = Convert.ToInt32(txtnumber.Text.Trim());
    int addedColumn = Convert.ToInt32(columnAdded.Value);
    for (int i = addedColumn + 1; i <= addedColumn + num; i++)
    {
        string name = "Unit";
        name = string.Concat(name, i);
        TemplateField test = new TemplateField();
        test.HeaderText = name;
        test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
        GridView1.Columns.Add(test);
       // ... Other code as you need
    }

}

希望这对你有所帮助。