Monday, December 7, 2009

ASP.NET - display records to grid view

Reference:

http://www.codersource.net/asp_net_grid_view_whidbey.aspx

Below is an example of using C#/ASP.NET to display content to a gridview (need to specify the object of "GridView1" in design view of ASP.NET first):

protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}

public void BindData()
{ // local variables
SqlConnection conn = null;
SqlCommand cmd = null;

try
{
conn = new SqlConnection("server=xxx;User ID=xxx;Password=xxx");
conn.Open();

cmd = new SqlCommand("select top(100) xxxx", conn);

SqlDataAdapter mySqlAdapter = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);

GridView1.DataSource = myDataSet;
GridView1.DataBind();

if (conn != null)
{
conn.Close(); conn = null;
}
}
catch (Exception ex)
{
if (conn != null)
{
conn.Close(); conn = null;

strLog = "[ (!!!Fail) Error=" + ex.Message + "]";
Response.Write(strLog);

}
}

Use code as below to add horizontal scrolling


// add code of GridView here


Use code as below to edit content of a row
1. Define functions


2. Function of Edit:

protected void GridView_MatchingServer_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView_MatchingServer.EditIndex = e.NewEditIndex;
BindData();
}

3. Function of Update
Add code as below to retrieve content of field being edited.

GridViewRow row = GridView_MatchingServer.Rows[e.RowIndex];
strMess1 = ((TextBox)(row.Cells[1].Controls[0])).Text; // RecID
strMess2 = ((TextBox)(row.Cells[3].Controls[0])).Text; // content of field

Where Cells[1] and Cells[3] represent the 1st and 3rd columns.

No comments: