Ajouter plusieurs lignes de données dans un gridview

termitus19 Messages postés 83 Date d'inscription mercredi 7 janvier 2015 Statut Membre Dernière intervention 23 juin 2021 - 11 oct. 2018 à 18:38
kritikas Messages postés 2 Date d'inscription samedi 12 janvier 2019 Statut Membre Dernière intervention 18 janvier 2019 - 17 janv. 2019 à 08:28
j'ai un gridview dans mon application web
je veux qu'à chaque fois je saisi des informations dans un textbox à l'aide d'un bouton qu'il soit ajouté dans le gridview
merci de m'aider stp

1 réponse

kritikas Messages postés 2 Date d'inscription samedi 12 janvier 2019 Statut Membre Dernière intervention 18 janvier 2019
Modifié le 5 août 2019 à 15:08
You may try this ASP.Net code it worked for me.

<asp:GridView ID="GridView1" runat="server" CssClass="Grid" AutoGenerateColumns="false"
    EmptyDataText="No records has been added.">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
    </Columns>
</asp:GridView>
<br />
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse">
<tr>
    <td style="padding-bottom: 10px">
        Name:<br />
        <asp:TextBox ID="txtName" runat="server" />
    </td>
</tr>
<tr>
    <td style="padding-bottom: 10px">
        Country:<br />
        <asp:TextBox ID="txtCountry" runat="server" />
    </td>
</tr>
<tr>
    <td style="width: 100px">
        <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
    </td>
</tr>
</table>

Binding the GridView using an Empty DataTable

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[2] {new DataColumn("Name"), new DataColumn("Country") });
        ViewState["Customers"] = dt;
        this.BindGrid();
    }
}
 
protected void BindGrid()
{
    GridView1.DataSource = (DataTable)ViewState["Customers"];
    GridView1.DataBind();
}


Add (Insert) multiple rows in GridView using DataTable

protected void Insert(object sender, EventArgs e)
{
    DataTable dt = (DataTable)ViewState["Customers"];
    dt.Rows.Add(txtName.Text.Trim(), txtCountry.Text.Trim());
    ViewState["Customers"] = dt;
    this.BindGrid();
    txtName.Text = string.Empty;
    txtCountry.Text = string.Empty;
}
0
Rejoignez-nous