Enable disable show hide controls in grdview edit mode RowEditing or PreRender method Asp.Net C# VB.Net

In many asp.net (C# VB.Net) forum i found that developers ask how to enable or disable or show or hide asp.net server side controls like textbox, label, checkbox, checkboxlist, radiobutton, radiobuttonlist & dropdownlist or combo box in GridView edit mode. Everyone using RowEditing event handler by using findcontrol method and editindex number. But there is an alternative, we can reference the above controls within GridView edit mode in PreRender method which is best i think. In PreRender method we can access each edit template controls so that we can easily hide or show or enable or disable those controls.

Objective/Outcome:
Enable disable controls in grdview edit mode RowEditing or PreRender Asp.Net Csharp VB.Net

To do the Example First Create 2 Database Tables:

CREATE TABLE [dbo].[Brand](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NOT NULL,
 CONSTRAINT [PK_Brand] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Product](
	[ID] [bigint] NOT NULL,
	[Name] [varchar](max) NULL,
	[Description] [varchar](max) NULL,
	[BrandID] [bigint] NULL,
 CONSTRAINT [PK_Product_2] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Now Insert Some Data:

INSERT INTO Brand Values(1,'Kohinoor')
INSERT INTO Brand Values(2,'Proctor & Gamble')
INSERT INTO Brand Values(3,'Telenor')
INSERT INTO Brand Values(4,'Unilever')

INSERT INTO PRODUCT VALUES(1,'Lux Beauty Soap','Product of Unilever',4)
INSERT INTO PRODUCT VALUES(2,'Tibbet Pomed','Winter Product',1)
INSERT INTO PRODUCT VALUES(3,'Data SIM','Subscriber Identity Module',3)
INSERT INTO PRODUCT VALUES(4,'Nippon','Color Television',1)

Now modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now add the GridView:

<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" 
        AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound" 
       
HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" 
        HeaderStyle-ForeColor="White" CellPadding="5" onprerender="GridView1_PreRender" 
        onrowediting="GridView1_RowEditing">
         <Columns>
             <asp:BoundField DataField="Name" HeaderText="Name"/>
             <asp:BoundField DataField="Description" HeaderText="Description" />
              
             <asp:TemplateField HeaderText="Brand">
             <ItemTemplate>
             <asp:Label ID="lblBrand" runat="server" Text='<%#Eval("Brand") %>'>
             </asp:Label>
             </ItemTemplate>
             <EditItemTemplate>
             <asp:DropDownList ID="cboBrand" runat="server"></asp:DropDownList>
             </EditItemTemplate>
             </asp:TemplateField>
              
             <asp:CommandField ShowEditButton="True" />            
        </Columns>
        </asp:GridView>

Now Bind The GridView with Data:
C# Code:

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

    private void BindGridView()
    {
        DataTable dt;
        String SQL = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" +
                    " FROM Product P, Brand B" +
                    " WHERE P.BrandID=B.ID";


        string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(sConstr))
        {
            using (SqlCommand comm = new SqlCommand(SQL, conn))
            {
                conn.Open();
                using (SqlDataAdapter da = new SqlDataAdapter(comm))
                {
                    dt = new DataTable("tbl");
                    da.Fill(dt);
                }
            }
        }
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

VB.Net Code:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindGridView()
        End If
    End Sub

    Private Sub BindGridView()
        Dim dt As DataTable
        Dim SQL As [String] = "SELECT P.ID ID, P.Name Name, P.Description Description, B.ID BrandID,B.Name Brand" & " FROM Product P, Brand B" & " WHERE P.BrandID=B.ID"


        Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
        Using conn As New SqlConnection(sConstr)
            Using comm As New SqlCommand(SQL, conn)
                conn.Open()
                Using da As New SqlDataAdapter(comm)
                    dt = New DataTable("tbl")
                    da.Fill(dt)
                End Using
            End Using
        End Using
        GridView1.DataSource = dt
        GridView1.DataBind()
    End Sub

Now handle RowDataBound handler to populate Template Column Controls:
C# Code:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if ((e.Row.RowState & DataControlRowState.Edit) > 0)
            {
                DropDownList cboBrand = (DropDownList)e.Row.FindControl("cboBrand");
                DataTable dt;
                String SQL = "SELECT * FROM Brand";

                string sConstr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(sConstr))
                {
                    using (SqlCommand comm = new SqlCommand(SQL, conn))
                    {
                        conn.Open();
                        using (SqlDataAdapter da = new SqlDataAdapter(comm))
                        {
                            dt = new DataTable("tbl");
                            da.Fill(dt);
                        }
                    }
                }

                cboBrand.DataSource = dt;
                cboBrand.DataTextField = "Name";
                cboBrand.DataValueField = "ID";
                cboBrand.DataBind();
                cboBrand.SelectedValue = ((DataRowView)e.Row.DataItem)["BrandID"].ToString();
                
                // You also control the show hide enable disable here.
                // But its not a good practice
                // cboBrand.Enabled = false;
            }
        }
    }

VB.Net Code:

    Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
                Dim cboBrand As DropDownList = DirectCast(e.Row.FindControl("cboBrand"), DropDownList)
                Dim dt As DataTable
                Dim SQL As [String] = "SELECT * FROM Brand"

                Dim sConstr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
                Using conn As New SqlConnection(sConstr)
                    Using comm As New SqlCommand(SQL, conn)
                        conn.Open()
                        Using da As New SqlDataAdapter(comm)
                            dt = New DataTable("tbl")
                            da.Fill(dt)
                        End Using
                    End Using
                End Using

                cboBrand.DataSource = dt
                cboBrand.DataTextField = "Name"
                cboBrand.DataValueField = "ID"
                cboBrand.DataBind()
                cboBrand.SelectedValue = DirectCast(e.Row.DataItem, DataRowView)("BrandID").ToString()

                ' You also control the show hide enable disable here.
                ' But its not a good practice
                ' cboBrand.Enabled = False
            End If
        End If
    End Sub

Now enable GridView Row Editing Mode:
C# Code:

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

VB.Net Code:

    Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
        GridView1.EditIndex = e.NewEditIndex
        BindGridView()
    End Sub

Now showing how to use GridView PreRender Method:
C# Code:

    protected void GridView1_PreRender(object sender, EventArgs e)
    {
        if (this.GridView1.EditIndex != -1)
        {
            DropDownList cboBrand = (DropDownList)GridView1.Rows[GridView1.EditIndex].FindControl("cboBrand");
            if (cboBrand != null)
            {
                // You can apply condition here
                cboBrand.Enabled = false;
            }

        }
    }

VB.Net Code:

Protected Sub GridView1_PreRender(sender As Object, e As EventArgs)
        If Me.GridView1.EditIndex <> -1 Then
            Dim cboBrand As DropDownList = DirectCast(GridView1.Rows(GridView1.EditIndex).FindControl("cboBrand"), DropDownList)
            If cboBrand IsNot Nothing Then
                ' You can apply condition here
                cboBrand.Enabled = False

            End If
        End If
    End Sub

Now run the project. Hope you will get a disable DropDownList control in GridView Edit mode.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Gridview, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

     

*