Pages

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

Oct 26, 2012

How to pass Eval value to javascript function from GridView ItemTemplate

Passing the Eval value to a javascript method is bit tricky.

You cannot pass directly as shown below.

<asp:LinkButton id='lnk' runat='server' OnClientClick='<%#Eval("columnname",
"javascript:testfun({0});")%>' />

Instead , the below way should work

<asp:LinkButton id='lnk' runat='server' OnClientClick='<%#Eval("columnname",
"javascript:testfun({0});")%>' />

Dec 8, 2011

How to set html link visible false depending on Eval function in grid view

Below is the html link in the grid view item template that sets visibility depending on the IsOnline values.

<a href = "www.google.com" style='<%# Eval("IsOnline").ToString() == "True" ? "display:block" : "display:none" %>' >link</a>

Aug 10, 2010

Simple Add,Edit,Update and Delete operations in GridView + Asp.net 3.5

Lets first create a table in MSAccess like below named Customer

Customer Table















Aspx Page:

Drag a gridview and fields and event as given below


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                DataKeyNames="ID" onrowcommand="GridView1_RowCommand"
                onrowdeleting="GridView1_RowDeleting"
                onrowediting="GridView1_RowEditing"
                onrowdatabound="GridView1_RowDataBound"
                onrowupdating="GridView1_RowUpdating">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true"/>
                    <asp:TemplateField HeaderText="Name">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtTName" runat="server"
                             Text='<%# Bind("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'>
                            </asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Age">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtTAge" runat="server"
                            Text='<%# Bind("Age") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>'>
                           </asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:CommandField ShowEditButton="True" />
                </Columns>
            </asp:GridView>

.cs page:
// Create a connection to Access Database.
OleDbConnection aConnection = new OleDbConnection
 ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\CustomerInfo.mdb");

// Binds grid on page load.

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


// Method to bind grid

private void bindGrid()
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        OleDbDataAdapter adap = null;
        DataSet ds = new DataSet();
        try
        {
            aConnection.Open();
            query = "SELECT * FROM Customer";
            cmd = new OleDbCommand(query, aConnection);
            adap = new OleDbDataAdapter(cmd);
            adap.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception)
        {
          
            throw;
        }
        finally
        {
            aConnection.Close();
        }

// To make the grid editable when edit button clicked

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bindGrid();
    }

// Performs Delete and Update operations

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int cusID = 0;
        GridView gv = (GridView)sender;
       // to find the Current ID selected.
        cusID = Convert.ToInt32(
        gv.Rows[Convert.ToInt32(e.CommandArgument)].Cells[0].Text);
        if (e.CommandName == "Delete")
        {
            DeleteCustomer(cusID);
        }
        if (e.CommandName == "Update")
        {
           // to find the edit text box  value.
           TextBox txtname = GridView1.Rows[Convert.ToInt32(e.CommandArgument)]
            .FindControl("txtTName") as TextBox;
           TextBox txtage = GridView1.Rows[Convert.ToInt32(e.CommandArgument)].
            FindControl("txtTAge") as TextBox;
            updateCustomer(txtname.Text, txtage.Text, cusID);
        }
    }

//To create an Alert before deleting the row in gridview.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        foreach (Control control in e.Row.Cells[3].Controls)
        {
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
                DeleteButton.OnClientClick =
                 "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }

// Method to Delete Customer Information

private void DeleteCustomer(int ID)
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        try
        {
            query = "DELETE FROM Customer WHERE ID=" + ID;
            cmd = new OleDbCommand(query, aConnection);
            aConnection.Open();
            cmd.ExecuteNonQuery();
            aConnection.Close();
            bindGrid();
          
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
          
        }
    }

// Method to update customer with edit values.

private void updateCustomer(string name, string age, int ID)
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        try
        {
            query = "UPDATE Customer SET Name='" + name + "',Age='" +
                         age + "' WHERE ID=" + ID;
            cmd = new OleDbCommand(query, aConnection);
            aConnection.Open();
            cmd.ExecuteNonQuery();
            aConnection.Close();
            GridView1.EditIndex = -1;
            bindGrid();
        }
        catch (Exception)
        {

            throw;
        }
    }

Above given is the code used to perform Edit,Update
and delete operations in a gridview.

Jul 12, 2010

How to show date alone in GridView BoundField when using DateTime as DataType in DataBase.


DateTime Formatting in GridView:
Usually we create a field with DataType DateTime in Database 
say for eg. MSAccess database.
Now when you show this in the GridView it shows Date along with 
time like 7/6/2010 8:10:12 PM
But you may be in situation to show only the Date alone.
like 7/6/2010
To do so, simple specify the format in the GridView BoundField like

<Columns>
    <asp:BoundField 
              DataField="Date1" 
              HeaderText="Date" 
              DataFormatString="{0:d}" />
</Columns>

Refer the below link for different other formats
http://msdn.microsoft.com/en-us/library/
system.web.ui.webcontrols.boundfield.dataformatstring.aspx

Jul 10, 2010

How to show a alert message or confirmation when deleting row from GridView without postback + Asp.Net

This is a basic logic needed in Grid-view while deleting a data. By mistake people may click
on the delete button and if there is no alert or confirmation, some valuable data may be lost.
Let's go for implementation, below is the grid-view


<asp:GridView ID="GridView2" runat="server"  AutoGenerateSelectButton="true"
            DataKeyNames="ID"  AutoGenerateDeleteButton="true"
            onrowdatabound="GridView2_RowDataBound" >
      <Columns>
                <asp:BoundField DataField="ID" HeaderText="SL.No" Visible="false"/>
                <asp:BoundField DataField="Project" HeaderText="Project" Visible="false"/>
      </Columns>
</asp:GridView>

In the above grid the two properties namely AutoGenerateSelectButton,
and AutoGenerateDeleteButton let you show the Select and
Delete button on the GridView.
Now on onrowdatabound event of the GridView we implement the logic like


  protected void GridView2_RowDataBound(object sender,
                                                            GridViewRowEventArgs e)
    {
        // Gets the Delete command column, which is the first column
        foreach (Control control in e.Row.Cells[0].Controls)
        {
            // Gets the Delete link button
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
               DeleteButton.OnClientClick =
               "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }
The above code will show you an alert message before deleting a row.

How to access ServerSide method from GridView's ItemTemplate

Calling a CodeBehind Method From GridView's ItemTemplate:


While working with GridView, there may be a case where 
we actually need to do some operations in serverside for 
which we may be in a need to call a server side
method from ItemTemplate of a GridView.


Say for example, 
I had a situation where i need to call a server side 
method (which return a string value) from ItemTemplate.
So i used a label in the ItemTemplate like 



<asp:TemplateField HeaderText="Testing">
<ItemTemplate>
<asp:Label ID="lblCustomerAge" Text='<%# GetCategory() %>' runat="server">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>


Here GetCategory is the server side method.Code-behind is given below

  protected string GetCategory()
    {
       // Do whatever you want here
        return "TestCategory"; // For eg. passing a string
    }

Jun 30, 2010

How to find the GridView RowID on SelectedIndexChanged Event of DropDownList inside ItemTemplate of GridView

Once there is a case where i need to bind a dropdownlist depending 
on the selection of other dropdownlist.
The above case is a usual one which we can do in a selectedIndexChanged Event. 
But here the twist is, 
I have both the dropdownlist inside a GridView as ItemTemplate.
So when i write a selectedIndexChanged how do i identify the actual row id of the GridView where the current DropDownList is present.
Here we go for the solution..
Write the below code to the selectedIndexChanged Event of the DropDownList



// First Identify the row in which the dropdown value has been changed
        GridViewRow gr = (GridViewRow)
            ((DataControlFieldCell)((DropDownList)sender).Parent).Parent;
 //find the control in the current row
        // selected dropdownlist
        DropDownList Projectddl = (DropDownList)gr.FindControl("ddlTest");
        // Dropdownlist to bind
        DropDownList Datumddl = 
               (DropDownList)(gr.FindControl("ddlSamp"));
        if (Projectddl.SelectedItem.Value == "SomeSelectedValue")
        {            
           // bind the second dropdownlist here
          Datumddl .DataSource = dTable;

          Datumddl .DataTextField  = member;
          Datumddl .DataValueField = member;
          Datumddl .DataBind();
        }

Jul 22, 2008

Add,Edit, Delete and View in GridView in Asp.net 2.0

Description
DataGrid plays very important component in ASP.Net Application. It covers most of the basic reports for which you do not need any reporting component like Crystal Report, Report Viewer etc.
Major concern with any data entry form is Add, Edit, Delete and View.


Assumptions-
We are using SQL Server Express editions as Database.
Table Name- Employees
Fields- EmpId, EmpName, Designation
Take GridView control on page and set the ID property to dgEmployees.
Go to property builder by right click on

GridView -> Show Smart Tag -> Edit Columns.

Uncheck Auto-Generate Field from the Property window.
Add three TemplateField Column for Employee Name, Designation, & Delete Button. Add Edit button from CommandField Group from Property Window.
TemplateField Colums have ItemTemplate,

Alternating Item Template,

Edit Template, Header Template, Footer Template.


Each template columns Item Template field contains Label Control & Edit Template contains TextBox control for Editing item. Set the Binding Field name to the Text Property of both controls for each template field to the respective Database Column Name

i.e Eval("EmpName").


Set the DataKeyNames property of GridView to Primary Key Column of DataBase i.e. EmpId.

This property binds the database column field value to each row of gridview as a Unique Identifier.
Set the data bindings for Delete Button for CommandArgument Eval("EmpId"); for saving the ID column value from database for fetching the ID field value while Deleting the Record.

Set the CommandName property to Delete Button to CMDDelete. The CommandName property can contain any string name which can be used to recognize the type of command invoked from gridview. Because when any of the event generated in GridVeiw it fires RowCommand Event. In this event we have to handle the Delete Button Code. Instead if you are using default Delete Button of GridView then register for RowDeleting event of GridView and for accessing Unique ID columnvalue from database you need to fetch the id from DataKeys collection of GridView.

For e.g.
int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);


Place the Textbox control in the grids Footer template for Adding new record. Set the CommandName to CMDAdd for Add button.
Register events for Edit, Update, Cancel button of gridview RowEditing, RowUpdating, RowCancelEditing.


View in GridView
To view data in gridview is very simple. Just create a DataSet using SqlDataAdapter̢۪s Fill method and set the GridViews DataSource Property to DataSet.
Create a Method to Bind the GridView to DataSource named BindGrid. This method fetches data from the GetEmployees method which returns DataSet from Employees table.
Call the BindGrid on Page_Load in !IsPostBack block to fill the grid by default.
private void BindGrid()
{
dgEmployees.DataSource = GetEmployees();
dgEmployees.DataBind();
}
private DataSet GetEmployees()
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection();
conn.ConnectionString =ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("Select * From Employees", conn);
try
{
da.Fill(ds);
return ds;
}
catch { }
finally
{
conn.Close();
conn.Dispose();
}
return null;
}


Edit in GridView
For Editing Register RowEditing event of GridView. To switch the normal mode to Edit mode of gridview EditIndex property plays important role. EditIndex specifies which row is in edit mode by setting RowIndex to it. By default EditIndex of gridview is -1 (Normal mode).

If you want to edit 3rd Row then set the EditIndex to 2 (Row index starts from 0,1,2..).
After setting editindex refresh the grid by calling BinGrid. GridViewEditEventArgs object knows the current row index so getting row index of the selected row in gridveiw is not big deal; just

e.NewEditIndex (e object of GridViewEditEventArgs).


protected void dgEmployees_RowEditing(object sender, GridViewEditEventArgs e)
{
dgEmployees.EditIndex = e.NewEditIndex;
BindGrid();
}


Cancel in GridView
For Cancel just reset the GridView editindex to default i.e. -1 and refresh the grid.
protected void dgEmployees_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
dgEmployees.EditIndex = -1;
BindGrid();
}


Update in GridView
For Update register RowUpdating event of the gridview. Find the Unique id for updating the row from DataKeys collection of gridview.
int EmpId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);
Find the controls in the selected row by using FindControl method of gridviews rows collection and collect data from the text boxes.


TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox;


TextBox txtdesign = dgEmployees.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox;


Finally update the row and refresh the grid.


if(txtname!=null && txtdesign!=null)
UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());
dgEmployees.EditIndex = -1;
BindGrid();


Complete code-
protected void dgEmployees_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int empId = Convert.ToInt32(dgEmployees.DataKeys[e.RowIndex].Value);
//Find Text boxex
TextBox txtname = dgEmployees.Rows[e.RowIndex].FindControl("txtEmpName") as TextBox;
TextBoxtxtdesign=dgEmployees.Rows[e.RowIndex].FindControl("txtDesignation") as TextBox;
if(txtname!=null && txtdesign!=null)
UpdateEmployee(empId, txtname.Text.Trim(), txtdesign.Text.Trim());
dgEmployees.EditIndex = -1;
BindGrid();
}


Custom Delete in GridView
For Delete register RowCommand event of the gridview. Find the Unique id for deleting the row from DataKeys collection of gridview. Check for CommanName and invoke delete method for the selected row.
protected void dgEmployees_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("CMDDelete"))
{
int EmpId = Convert.ToInt32(e.CommandArgument);
DeleteEmployee(EmpId);
//Refresh Grid
BindGrid();
}
}
Add in GridView
Adding from GridView is just some trick with Footer Template. I added textboxes and a add button in the footer row of the gridview. When u are in Normal mode it is visible else it is invisible to synchronize between edit and add.
Like Updating find the Textbox and pass the values to Addemployee method like
else if (e.CommandName.Equals("CMDAdd"))
{
TextBox txtname = dgEmployees.FooterRow.FindControl("txtEmpName") asTextBox;
TextBox txtdesign = dgEmployees.FooterRow.FindControl("txtDesignation") as TextBox;
if (txtname != null && txtdesign != null)
{
AddEmployee(txtname.Text.Trim(), txtdesign.Text.Trim());
BindGrid();
}
}
The Complete code for EditEmployee, AddEmployee, UpdateEmployee, DeleteEmployee is in Source File.

The code should be in RowCommand event only. Due to this we use CommandName for different button control to differentiate between the type of code to be handled by gridview.

Jun 18, 2008

How to Implement themes to GridView in asp.net2.0

Introduction:
The theme of this article is Themes. I will show you that what Themes are used for and how you can make you own Themes quickly and easily. This is a multi series article so stay tuned for the rest of the series. What's up with Themes? Hey! we got CSS (Cascading Style Sheets) so why do we need Themes? The thing about CSS is that it only exposes some fixed style properties which we can use. If we want to change some property like AlternatingItemStyle of the GridView control we will not be able to do this by using simple CSS. Themes allow you to change the control properties. This mean you can change most of the properties exposed by any server control in ASP.NET 2.0.

Gettting Started With Themes: Let's get started with Themes. The first thing that you need to do is to add a skin file. Once you try to add a new skin file ASP.NET will make a folder called App_Themes in which all Themes will be placed. After the App_Themes folder has been created you can simply add .skin files inside the App_Themes folder. You can name the Theme files according to their action. Like if you are adding a Theme which makes the appearance of your page orange you can name is [YourSideName]_Orange_Theme. You can name it anything you want from orange Theme to "Yellow Banana" Theme.

What is in that Skin?
Skin files contains the definition of the server controls on which the Themes will be applied. Here is my Skin file called "Red" whose purpose is to make the GridView red.

As, you might have already noticed that the GridView definition does not contain the ID attribute. That is because this Theme is applied to all the GridViews on the page. There are couple of ways that you can apply different Themes for the same server control.

Applying Themes: There are various ways to apply the Theme to the page. The simplest one of them is to use the Page directive to apply the Theme to the current page.
The above will apply the Theme to the current page. If you wish to apply the same Theme to all the pages of your website then it is a better idea to define the Themes in the configuration file.
Eg:




You can also apply Themes dynamically using the Page.Theme property. The thing to remember about applying the Themes programmatically is that you can only apply it inside the Page_PreInit event.
Check out the code below which applies the Theme at runtime. protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "Green";
}

One thing that you need to remember is that when you set the Theme at different stages the Theme that is set dynamically takes precedence over the Page directive and Web.config. This means that if you have define your Theme to be "Blue" in Web.config and "Green" is Page directive and "Red" dynamically then the Theme set for the page will be set "Red". There is much more to cover in Themes which will be covered in later articles.
Reference: GridViewGuy