Showing posts with label GridView. Show all posts
Showing posts with label GridView. Show all posts

Monday, June 18, 2012

Set selected value of DropDownList in GridView EditItemTemplate


In Asp.Net the GridView supports Edit mode by means of configuring the controls in the EditItemTemplate.

For Textboxes, setting value in the Edit mode is straight forward, we can just set the Text property and the value will get displayed while editing the row.


Monday, May 21, 2012

GridView CommandArgument, passing multiple values

A Button or a link button in a GridView can pass a value to the RowCommand event in the code behind file using the CommandArgument property.


<asp:GridView
ID="grdEmployee"
runat="server"
OnRowCommand=" grdEmployee_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:LinkButton
ID="lnkname"
runat="server"
Text='<%#Eval("EMPLOYEE_NAME") %>'
CommandArgument='<%#Eval("EMPLOYEE_ID") %>' CommandName="linkButton">
asp:LinkButton>
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>

Here the column is a link button column and will display the employee name, on clicking the link button the RowCommand event of the GridView is fired, and we are passing the EMPLOYEE_ID value to the row command property.
protected void grdEmployee_RowCommand(object s, GridViewCommandEventArgs e)
{
     int intEmpId = 0;
     if (e.CommandName == "linkButton")
     {
          intEmpId = Convert.ToInt32(e.CommandArgument);
     }

}

This is fine for passing a single value to the code behind event, what if we need to pass more than one value to the code behind event, here is the code to acchieve the same.

Here we are passing the Employee_ID and Manager_ID values to the code behind event.

<asp:GridView
ID="grdEmployee"
runat="server"
OnRowCommand=" grdEmployee_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:LinkButton
ID="lnkname"
runat="server"
Text='<%#Eval("EMPLOYEE_NAME") %>' CommandArgument='<%#Eval("EMPLOYEE_ID") + ","+Eval("MANAGER_ID") %>'
CommandName="linkButton">
asp:LinkButton>
ItemTemplate>
asp:TemplateField>
Columns>
asp:GridView>

Here is the code behind logic to receive the multiple values passed through the CommandArgument

protected void grdEmployee_RowCommand(object s, GridViewCommandEventArgs e)
{
int intEmpId = 0;
int intMgrId = 0;
     if (e.CommandName == "linkButton")
     {
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
            intEmpId = Convert.ToInt32(commandArgs[0]);
            intMgrId = Convert.ToInt32(commandArgs[1]);        
     }
}

That’s it we have now passed multiple values using the CommandArgument property and received the same in the RowCommand event of the code behind file.

Friday, May 4, 2012

DataTable SORT using LINQ

We shall see, how to implement a Client side DataTable SORT, using LINQ, without hitting the database. 

First we will define the GridView control in the .aspx page, which will display the results of the filtered DataTable here is the code


<asp:GridView
ID="grdUsers"
runat="server"
AutoGenerateColumns="true">
   
<HeaderStyle
BackColor="Navy"
ForeColor="White"
Font-Bold="true" />
   
<RowStyle
BackColor="White"
ForeColor="Black" />
   
<AlternatingRowStyle
BackColor="Wheat"
ForeColor="Black" />

</asp:GridView>

Once we are done with the declaration of the GridView tag, we can switch to the code behind file (.cs/.vb file) to implement the DataBinding and SORT logic for the DataTable. Here is the code for the DataTable filter

string strSQL = "SELECT * FROM USERS";
DataSet dsUsers = new DataSet();
dsUsers = DataAccessLayer.GetDataSet(strSQL,"dtUSers");
//
// Implement your own DataAccess logic here to get data from the DB.
//
// SORT the DataTable using a LINQ Expression
DataTable dtSortedTable = dsUsers.Tables["dtUsers"].AsEnumerable()
.OrderBy(row => row.Field<string>("USER_NAME"))            
.CopyToDataTable();
//
grdUsers.DataSource = dtSortedTable;
grdUsers.DataBind();

Here the DataTable is ordered by the column USER_NAME

To sort the column in the Descending order we can use the Expression

.OrderByDescending(row => row.Field<string>("USER_NAME"))

That’s it we have sorted the column of DataTable control using LINQ expression.

Related Post

DataTable Filter using LINQ

We shall see, how to implement a Client side DataTable Filter using LINQ, without hitting the database. 

First we will define the GridView control in the .aspx page, which will display the results of the filtered DataTable here is the code


<asp:GridView
ID="grdUsers"
runat="server"
AutoGenerateColumns="true">
   
<HeaderStyle
BackColor="Navy"
ForeColor="White"
Font-Bold="true" />
   
<RowStyle
BackColor="White"
ForeColor="Black" />
   
<AlternatingRowStyle
BackColor="Wheat"
ForeColor="Black" />

</asp:GridView>

Once we are done with the declaration of the GridView tag, we can switch to the code behind file (.cs/.vb file) to implement the DataBinding and Filter logic for the DataTable. Here is the code for the DataTable filter

string strSQL = "SELECT * FROM USERS";
DataSet dsUsers = new DataSet();
dsUsers = DataAccessLayer.GetDataSet(strSQL,"dtUSers");
//
// Implement your own DataAccess logic here to get data from the DB.
//
// Filter the DataTable using a LINQ Expression
DataTable dtFilterTable = dsUsers.Tables["dtUsers"].AsEnumerable()
            .Where(row => row.Field<String>("USER_NAME").Contains(txtFilter.Text))
            .CopyToDataTable();
//
grdUsers.DataSource = dtFilterTable;
grdUsers.DataBind();

Here the DataTable is filtered on the USER_NAME column based on the filter text entered in the txtFilter TextBox.

That’s it we have filtered the contents of DataTable control using LINQ filters.

Binding a DataTable to GridView

Asp.net provides a GridView controls to display table data in Asp.Net pages, the GridView needs to be provided with data to populate the same in the UI.

The GridView accepts many types of datasources like DataTable, DataReader, List etc, today we shall see on how to bind the data from a DataTable to a GridView control.


Refer the post Binding a C# List to a GridView control, to Bind a List to the GridView.

First we need to define the GridView control in the .aspx page, here is the code

<asp:GridView
ID="grdUsers"
runat="server"
AutoGenerateColumns="true">
   
<HeaderStyle
BackColor="Navy"
ForeColor="White"
Font-Bold="true" />
   
<RowStyle
BackColor="White"
ForeColor="Black" />
   
<AlternatingRowStyle
BackColor="Wheat"
ForeColor="Black" />

</asp:GridView>

Once we are done with the declaration of the GridView tag, we can switch to the code behind file (.cs/.vb file) to implement the DataBinding logic. Here is the code to bind data to the GridView

string strSQL = "SELECT * FROM USERS";
DataSet dsUsers = new DataSet();
dsUsers = DataAccessLayer.GetDataSet(strSQL, "dtUSers");
//
// Implement your own DataAccess logic here to get data from the DB.
//
grdUsers.DataSource = dsUsers.Tables["dtUSers"];
grdUsers.DataBind();

The DataSet & DataTable objects are present in the System.Data Assembly; hence make sure that a reference to this assembly is added to the project before building the Project.
Build and run the project, you will be able to see the result of the query displayed in the Asp.net form in the GridView control.

That’s it we have seen, how to bind a DataTable to a GridView control.

Related Posts


Thursday, May 3, 2012

GridView Filter using LINQ

We shall see, how to implement a Client side GridView Filter using LINQ, without hitting the database. We will be using a C# List as the data source to the Grid View, instead we can also use a DataTable.

To know more about binding a C# List to a GridView refer the post Binding a C# List to a GridView control

First let us create a class whose objects will be stored in the List (refer post Binding a C# List to a GridView control)


Next, let us create a list of objects based on our class clsCountry and store them in a List object. Here is the code for the List


List<clsCountry> lstCountry = new List<clsCountry>();

lstCountry.Add(new clsCountry("USA""United States"));

lstCountry.Add(new clsCountry("UK""United Kingdon"));

lstCountry.Add(new clsCountry("IND""India"));

lstCountry.Add(new clsCountry("RUS", "Russia"));
lstCountry.Add(new clsCountry("SA", "South Africa"));
lstCountry.Add(new clsCountry("AUS", "Australia"));

Finally we shall bind the List object lstCountry to a GridView control. Here the code to bind the data.


grdCountry.DataSource = lstCountry;

grdCountry.DataBind();


Now this will bind all the value to the GridView, to filter the values we need to add a LINQ filter and bind the filtered values to the GridView, as follows

var filteredCountries = from c in lstCountry
where c.CountryName.Contains(txtFilter.Text)
select c;

grdCountry.DataSource = filteredCountries;
grdCountry.DataBind();

Here the LINQ expression takes the filter text from the textbox txtFilter.Text, and applies the filter on the List object, the result of the filter expression in bound to the GridView.

In this example we have used a List object, instead we can also use a DataTable and apply the LINQ filter to the DataTable.

That’s it we have filtered the contents of GridView control using LINQ filters.


Related Post
Binding a C# List to a GridView control
What is LINQ?

Binding a C# List to a GridView control

In general we use a DataTable or a DataReader to bind data to a GridView control, today we shall see on how to bind a C# List to a GridView control.


To know more about the C# List object refer to the post C# List

First let us create a class whose objects will be stored in the List, here is the code for the class.



public class clsCountry

{

    public string _CountryCode;

    public string _CountryName;

    //

    public clsCountry(string strCode, string strName)

    {

        this._CountryCode = strCode;

        this._CountryName = strName;

    }

    //

    public string CountryCode

    {

        get {return _CountryCode;}

        set {_CountryCode = value;}

    }

    //

    public string CountryName

    {

        get { return _CountryName; }

        set { _CountryName = value; }

    }

}


Next, let us create a list of objects based on our class clsCountry and store them in a List object. Here is the code for the List

List<clsCountry> lstCountry = new List<clsCountry>();

lstCountry.Add(new clsCountry("USA", "United States"));

lstCountry.Add(new clsCountry("UK", "United Kingdon"));

lstCountry.Add(new clsCountry("IND", "India"));


Finally we shall bind the List object lstCountry to a GridView control. Here the code to bind the data.


grdCountry.DataSource = lstCountry;
grdCountry.DataBind();

Notice that the columns bound to the GridView control are mapped to the Properties of the class CountryCode and CountryName, hence make sure to create properties for every member of the class so that they can be used while binding the data to controls.


That’s it we have bound the contents of a C# List object to a GridView control.

Related Post
1. C# List

2. Binding a C# List to a DropDownList control