![]() |
Desktop Development »
Grid & Data Controls »
DataGrid and DataView
Intermediate
License: The Code Project Open License (CPOL)
Datagrid - Editing, Updating, Cancel, Selecting RowsBy Muhammad AhmadHow to work with data grid view |
C#, .NET, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
Microsoft .NET Framework ships with many useful controls. These controls make the life of the developer easy by providing them with the functionality that they want.
Among those many controls is the DataGrid control which helps the developer to display the data on the screen in the format of an arranged table. Datagrid is one of the 3 templated controls provided by the Microsoft. NET Framework. The other two are DataList and the Repeator control. Many new controls are being developed everyday but their basic idea is inherited from the classic DataGrid control.
In this article, we will see the most common use of the datagrid control. Let's set up our datagrid.
Let's first set up our datagrid.
datagrid control from your toolbox to the webform. datagrid will appear as a simple table. datagrid pretty by selecting the Auto format features. Okay your datagrid is set up, let's add some columns.
Adding the bound columns in the datagrid is pretty simple.
datagrid and select Property Builder. Note: Please also note that the button type should be link button or else it won't work.
In this demo, I am storing the database connection in the Web.config file. The database name is DBSnippets, which has one table known as tblPerson. Here is the web.config file.
<configuration>
<appSettings>
<add Key="ConnectionString" value="server=localhost;database=DBSnippets">
</appSettings>
</configuration>
Okay till now we have made the Datagrid and also saved the connection string in the web.config file. Now the time has come to code and handle the events.
Let's first make the BindData method which will retrieve the contents from the database and bind it on the screen. This will be one of the most important methods since it will be called whenever the page is loaded for the first time.
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}
As you see, the BindData method is called when the page is not posted back. Now let's see the BindData method in detail.
public void BindData()
{
SqlCommand myCommand = new SqlCommand("SP_SELECT_PERSONS",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds,"tblPerson");
myConnection.Open();
myCommand.ExecuteNonQuery();
myDataGrid.DataSource = ds;
myDataGrid.DataBind();
myConnection.Close();
}
SqlCommand object and name it myCommand. The SqlCommand object takes a stored procedure as an input and the SqlConnection. DataAdapter object named as myAdapter. myDataGrid.DataBind() binds the datagrid to the page. Don't forget to bind the grid or else it won't be displayed. Now let's look at the stored procedure.
CREATE PROCEDURE SP_SELECT_PERSONS
AS
SELECT * FROM tblPerson GO
As you can see, the above Stored Procedure is pretty simple. All we are doing is just selecting all the columns from the table person.
Let's now make the Edit method which will display textboxes inside the datagrid so that a user can insert data. This sort of editing is also known as Inline editing.
Making datagrid editable is pretty simple. All you do is code few lines in the EditCommand event of the datagrid. You can view all the events supported by DataGrid by selecting properties and than selecting the Thunder/Flash yellow sign at the top of the properties window.
Let's call our Edit DataGrid event Edit_DataGrid.
private void Edit_DataGrid
(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// We use CommandEventArgs e to get the row which is being clicked
// This also changes the DataGrid labels into Textboxes so user can edit them
myDataGrid.EditItemIndex = e.Item.ItemIndex;
// Always bind the data so the datagrid can be displayed.
BindData();
}
When the Edit link button is clicked, your DataGrid will look something like this:
As you see, when you click the edit link the update and the cancel link button automatically appear.
Let's now see the code for the Cancel Event. Cancel event is used when you are in the edit mode and you change your mind about not editing. So you click the cancel link button and the Datagrid returns back to its original condition.
private void Cancel_DataGrid
(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// All we do in the cancel method is to assign '-1' to the datagrid editItemIndex
// Once the edititemindex is set to '-1'
// the datagrid returns back to its original condition
myDataGrid.EditItemIndex = -1;
BindData();
}
Okay now we come to a slightly difficult step. We will carefully look at the Update method and see how it works.
private void Update_DataGrid(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox();
cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0];
SqlCommand myCommand = new SqlCommand("SP_UpdatePerson",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("@PersonName",SqlDbType.NVarChar,50));
myCommand.Parameters["@PersonName"].Value = cName.Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
myDataGrid.EditItemIndex = -1;
BindData();
}
Let's now dig into this method and see what's going on.
Update_DataGrid, this event is fired when you click the update link button which appears after clicking the edit button. TextBox type and call it cName. The reason of declaring a TextBox is that the value that we want is inside the TextBox which is inside the DataGrid control. SqlCommand object which takes stored procedure "SP_UpdatePerson", which will be discussed afterwards. PersonName. editItemIndex property of the DataGrid '-1' which will bring the datagrid back to its original form, i.e. without any textboxes. datagrid. CREATE PROCEDURE SP_UpdatePerson
@PersonName nvarchar(50)
AS
UPDATE tblPerson SET PersonName = @PersonName WHERE PersonName = @PersonName;
Another cool feature of the Datagrid control is that you can select any row from the datagrid and it will be displayed as the highlighted row in the grid.
The highlight row event is called SelectedIndexChanged event. The event is called when the select column is clicked. The select column can be added to the datagrid using the property builder, just like we added "edit/cancel/update" link buttons.
// This event is fired when the Select is clicked
private void Select_DataGrid(object sender, System.EventArgs e)
{
// prints the value of the first cell in the DataGrid
Label2.Text += myDataGrid.SelectedItem.Cells[0].Text;
}
This method is pretty simple. When the datagrid select link button is pressed, we retrieve the item from the datagrid which is residing on the same row on which the link button is pressed. As we can see above in the code, we are retrieving the value from the first column of the datagrid.
I hope you all liked the article.
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 18 Jun 2009 Editor: Deeksha Shenoy |
Copyright 2009 by Muhammad Ahmad Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |