Saturday, 29 August 2009

Playing With GridView (Part 1)

Hello Friends.......
Gridview is the most common data control in asp.net 2.0.It is a very rich control indeed.Here we are going to learn how to use gridview control for handling data.Here we will create a gridview control to retrieve the data from the database and we will perform the operation like show, update, cancel, paging, sorting, add and delete on the retrieved data.

So lets start the fun.First of all just create a create a Gridview control on your aspx page(you can do this by simply draging 'n' dropping the gridview control on the page)
Now right click on the gridview control and choose 'Auto Format' from the context menu.Now from the Auto format window you can simply choose the scheme acoording to your interest.
(in our case, we have selected the 'state' scheme).After selecting the scheme , your control will appear like this in apspx page :


< asp:GridView id="GridView1" width="70%" runat="server" style="position: relative"> BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" DataKeyNames="Name" CellPadding="3" AllowPaging="True" AutoGenerateColumns="false" AllowSorting="True" GridLines="Horizontal" PageSize="5" >

< FooterStyle backcolor="#B5C7DE" forecolor="#4A3C8C">
< RowStyle backcolor="#E7E7FF" forecolor="#4A3C8C">
< PagerStyle backcolor="#E7E7FF" forecolor="#4A3C8C" horizontalalign="Right">
< SelectedRowStyle backcolor="#738A9C" bold="True" forecolor="#F7F7F7">
< HeaderStyle backcolor="#4A3C8C" bold="True" forecolor="#F7F7F7">
< AlternatingRowStyle backcolor="#F7F7F7">
< /asp:GridView>

Now bind the columns of your database table to the gridview in the following manner :
(Insert Before footer template tag.....)

< Columns>
< asp:TemplateField HeaderText="Name">
< ItemTemplate>
< %# Eval("Name") %>
< /ItemTemplate>
< EditItemTemplate>
< asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' />
< /EditItemTemplate>
< ItemStyle Font-Bold="True" />
< /asp:TemplateField>
< asp:TemplateField HeaderText="Designation">
< ItemTemplate>
< %# Eval("Designation") %>
< /ItemTemplate>
< EditItemTemplate>
< asp:TextBox ID="txtDesig" runat="server" Text='<%# Bind("Designation") %>' />
< /EditItemTemplate>
< ItemStyle Font-Bold="True" />
< /asp:TemplateField>
< asp:TemplateField HeaderText="Company">
< ItemTemplate>
< %# Eval("Company") %>
< /ItemTemplate>
< EditItemTemplate>
< asp:TextBox ID="txtComp" runat="server" Text='<%# Bind("Company") %>' />
< /EditItemTemplate>
< ItemStyle Font-Bold="True" />
< /asp:TemplateField>
< asp:TemplateField HeaderText="Experience">
< ItemTemplate>
< %# Eval("Experience") %>
< /ItemTemplate>
< EditItemTemplate>
< asp:TextBox ID="txtExp" runat="server" Text='<%# Bind("Experience") %>' />
< /EditItemTemplate>
< ItemStyle Font-Bold="True" />
< /asp:TemplateField>
< asp:CommandField ShowEditButton="True" />
< /Columns>

And in design view, it will apeear like this :



Now moving towards the code behind(aspx.cs) part, we have to retrieve the data from the database and bind it to the Gridview control.
here for retrieving and binding purpose, we create a simple BindGrid function as follows :

public void BindGrid()

{

con.Open();

DataSet ds = new DataSet();

string str = "select Name, Designation, Company, Experience from Profile";

SqlDataAdapter da = new SqlDataAdapter(str, con);

da.Fill(ds);

GridView1.DataSource = ds;

GridView1.DataBind();

con.Close();

}


........and on the page load event, we will call the function in the following manner :

SqlConnection con = new SqlConnection("Data Source=kartik;Initial Catalog=MyNetwork;Integrated Security=true");

protected void Page_Load(object sender, EventArgs e)

{

if(!Page.IsPostBack)

BindGrid();

}


We will also use the PageIndexChanging event of gridview for implementing Page Indexing...............

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

GridView1.PageIndex = e.NewPageIndex;

BindGrid();

}


.............Now we are ready to see how our gridview look in web borowser.So just run your application and check your gridview in the browser.The gridview will look like this at run time :

................Now we add the Edit button to our gridview control.Simply right click on the control, choose 'show smart tag' from the context menu, select 'Edit Columns' and then select 'command field' from the field window....after cicking on 'command field' , you will find the '
edit,Update,cancel' button option, select it and add it.It will now be showing in your 'selected field' window.Now your gridview control will appear like this :



............Now we will use the Rowediting, Rowcancelin and Rowupdating events of our gridview control.First of all select the RowEditing event of your gridview control and the following coding to it :

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{

GridView1.EditIndex = e.NewEditIndex;

BindGrid();

}

......................Now select the RowCancelingEdit event and add the following code to it :

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{

GridView1.EditIndex = -1;

BindGrid();

}

.............And finaly select the RowUpdating event and add following code to it :

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

string NameOld = Convert.ToString(GridView1.DataKeys[e.RowIndex].Value);

TextBox Name = (TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[1];

TextBox Desig = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[1];

TextBox Comp = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[1];

TextBox Exep = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[1];

con.Open();

string str = "update Profile set Name = '" + Name.Text + "', Designation = '" + Desig.Text + "', Company = '" + Comp.Text + "', Experience = '" + Exep.Text + "' where Name = '" + NameOld + "' ";

SqlCommand com = new SqlCommand(str, con);

com.ExecuteNonQuery();

GridView1.EditIndex = -1;

con.Close();

BindGrid();


}

Now we are ready to run our applcation again.........so just run your application and click on any edit button.....Gridview will appear like this :


...............Now simply make changes and update/cancel the records according to your choice.In the next part, We will learn how to add new record to the gridview control and how to delete records from the gridview control.

.....................contd.

No comments: