Cet exemple permet de créer une gridView, puis de parcourir ligne à ligne ses valeurs pour enfin les afficher.
Page aspx :
<table width="100%">
<tr>
<td align="center">
<asp:GridView runat="server"
ID="gvList"
AutoGenerateColumns="false"
Width="400px">
<Columns>
<asp:TemplateField HeaderText="Nom" ItemStyle-Width="50%">
<ItemTemplate>
<asp:TextBox runat="server"
ID="txtNom"
Width="98%" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Prénom" ItemStyle-Width="50%">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtPrenom" Width="98%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td align="center">
<asp:Button runat="server"
ID="btnValid"
Text="Valider"
OnClick="btnValid_Click" />
</td>
</tr>
<tr>
<td align="center">
<asp:TextBox TextMode="MultiLine"
ID="txtResult"
runat="server"
Height="200px"
Width="60%" />
</td>
</tr>
</table>
CodeBehind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Création d'une dataTable de 10 lignes et de deux colonnes
DataTable dt = new DataTable("dt");
dt.Columns.Add("Nom");
dt.Columns.Add("Prenom");
for (int i = 0; i < 10; i++)
{
DataRow newRow = dt.NewRow();
dt.Rows.Add(newRow);
}
gvList.DataSource = dt;
gvList.DataBind();
}
}
/// <summary>
/// Classe interne Personne
/// </summary>
internal class Personne
{
public string Nom { get; set; }
public string Prenom { get; set; }
}
/// <summary>
/// Action sur le bouton valider, ajout des personnes saisies dans une IList
/// </summary>
protected void btnValid_Click(object sender, EventArgs e)
{
IList<Personne> lsPersonne = new List<Personne>();
foreach (GridViewRow row in gvList.Rows)
{
Personne personne = new Personne();
TextBox txtNom = row.FindControl("txtNom") as TextBox;
personne.Nom = txtNom.Text;
TextBox txtPrenom = row.FindControl("txtPrenom") as TextBox;
personne.Prenom = txtPrenom.Text;
lsPersonne.Add(personne);
}
AffichePersonne(lsPersonne);
}
/// <summary>
/// Affichage des personnes dans une TextBox multiligne
/// </summary>
/// <param name="lsPersonne">Une liste de personnes</param>
private void AffichePersonne(IList<Personne> lsPersonne)
{
txtResult.Text = string.Empty;
foreach (Personne personne in lsPersonne)
{
txtResult.Text += personne.Nom + " " + personne.Prenom +"\r\n";
}
}