Utilizza il codice che ti ho scritto nel Page_Load (nella if che riguarda il postback) per caricarla.
Per modificarla, puoi farlo in vari modi.
Uno di questi è un CommandField aggiunto come colonna alla Grid. E' il modo "inline", le labels si trasformano in textbox, ti permettono la modifica del record e di aggiornarlo sul db.
ASPX:
codice:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false"
onrowediting="gv_RowEditing" onrowupdated="gv_RowUpdated"
onrowupdating="gv_RowUpdating" onrowcancelingedit="gv_RowCancelEdit">
<Columns>
<asp:BoundField DataField="nome" HeaderText="NOME" />
<asp:BoundField DataField="cognome" HeaderText="COGNOME" />
<asp:CommandField ButtonType="Link" ShowEditButton="true" />
</Columns>
</asp:GridView>
.CS
codice:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class GridView_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDati();
}
}
protected void BindDati()
{
using (SqlConnection connection = new SqlConnection("Data Source=XXXXXX;Initial Catalog=XXXXX;Persist Security Info=True;User ID=XXX;Password=XXXXXX"))
{
// crea l'oggetto command
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT nome, cognome FROM [tb_utenti]";
// Apre la connessione e riempie il datareader
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
gv.DataSource = reader;
gv.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
protected void gv_RowCancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gv.EditIndex = -1;
BindDati();
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
BindDati();
}
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gv.Rows[e.RowIndex];
string nuovoNome = ((TextBox)(row.Cells[0].Controls[0])).Text;
string nuovoCognome = ((TextBox)(row.Cells[1].Controls[0])).Text;
// FAI L'UPDATE SUL DB CON I NUOVI DATI
}
protected void gv_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
//
}
}