Thursday, 29 December 2011

call webuser control dynamically


Introduction: Hello friends, in this article i will explain that how we can call webuser control at the .cs page dynamically using sapx.cs code. The webuser control is very useful control in asp.net. with the help of the webuser control the part of the code can be seprated from the .aspx.cs page. According to my experience , we can use webuser control where some designning issues are created, then you can create webuser control and call that webuser control at the part of the .aspx page.

Implementation: create a new website abb a page named table_call_web_user_control.aspx.  and a webuser control named talble_user_control.ascx.  Below  i am giving the complete code for the html page and .cs page and the ascx page and ascx.cs page. 

Code for talble_user_control.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="talble_user_control.ascx.cs" Inherits="talble_user_control" %>
<table >
            <tr>
                <td>
                    Enter value</td>
                <td>
                    <asp:TextBox ID="txt_table" runat="server" MaxLength="8" placeholder="hh" ToolTip="Enter number"></asp:TextBox>
                      <asp:RegularExpressionValidator ID="regular_exp_for_txt_ans" runat="server" ErrorMessage="Enter digits only"
                    ControlToValidate="txt_table" ValidationExpression="^-{0,1}\d+$" BackColor="Beige"></asp:RegularExpressionValidator>
                </td>
            </tr>
            <tr>
                <td>
                    </td>
                <td>
                    <asp:Button ID="btn_table" runat="server" onclick="btn_table_Click"
                        Text="Sumbit" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lbl_table" runat="server" BorderColor="Brown"></asp:Label>
                </td>
            </tr>
        </table>
Code for talble_user_control.ascx.cs:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
// this namespace in necessary for the stringbuilder
using System.Text;

public partial class talble_user_control : System.Web.UI.UserControl
{
    // here m declaring the variale
    int n;
    // here m declairing a StringBuilder class
    StringBuilder str = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        txt_table.BackColor = System.Drawing.Color.FromName("#DEB887");

    }
    protected void btn_table_Click(object sender, EventArgs e)
    {

        if(txt_table.Text=="")
        {

            lbl_table.Text = "Enter any number";
        }
        else
        {
        // in the n variable m catching the value from the textbox, means when user will enter the value that value
        // will store inside the n variable
        n = Convert.ToInt32(txt_table.Text);
        // here m declaring the variable named i as integer
        int i;
        // for loop will work for 10 time from 1 to 10
        for (i = 1; i <= 20; i++)
        {
            // this line will print the table
            //n + " * " + i + " = " + n*i
            // first n means value enter by the user
            //i mean 1,2,3 upto ten
            //n*i mean multiplication suppose user enters 3 then..
            // 3*1  3*2 upto 10
            // above commented 4 lines print the output  as like
            //3 * 1  = 3
            //3 * 2  = 6
            // and so on upto ten

            str.Append(n + " * " + i + " = " + n * i + "<br/>");
        }
        // here m print the output inside the label which will come from the stringbuilder
        lbl_table.Text = str.ToString();
     

        // here m emptying the textbox after printing the output
        txt_table.Text = "";
        }

    }
}

Code for talble_user_control.aspx page

<head runat="server">
    <title>Table</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   <%-- here i am placing PlaceHolder for calling webusercontrol--%>
     <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
    </div>
    </form>
</body>
</html>




Code for talble_user_control.aspx.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class table_call_web_user_control : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // here m calling dynamically Webuser control at this page and add it into the PlaceHolder1  control
        Control add = (Control)(Page.LoadControl("talble_user_control.ascx"));
        PlaceHolder1.Controls.Add(add);
    }
}



See output in this image:



Conclision: In above code, i just get the get the table by using string builder inside the webuser control . This code is very helpful for every .net developer.






Friday, 18 November 2011

Row command event of the gridview


Introduction: Hello guys, in this article i will explain that how we can  work with the rowcommand event of the gridview. This article will very helpful for the .net developers.

Implementation: Create a page named rw_commamnd.Place  four textboxes and a button and a gridview. And set their id as txt_name,txt _age,txt_paswrd and txt_repswrd respectively.  


Code for .aspx page:
head runat="server">
    <title>Row command event</title>
 
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <table >
            <tr>
                <td>
                    Name</td>
                <td>
                    <asp:TextBox ID="txt_name" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td >
                    Age</td>
                <td>
                    <asp:TextBox ID="txt_age" runat="server"></asp:TextBox>
                </td>
            </tr>
     
            <tr>
                <td >
                    Password</td>
                <td>
                    <asp:TextBox ID="txt_pswrd" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Retype_password</td>
                <td>
                    <asp:TextBox ID="txt_repswrd" runat="server" TextMode="Password"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &</td>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
                </td>
            </tr>
        </table>
   
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        onrowcommand="GridView1_RowCommand" CellPadding="4" ForeColor="#333333"
        GridLines="None">
        <RowStyle BackColor="#E3EAEB" />
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Age">
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Eval("Age") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Login_status">
            <%--here am placing the link button and set its commandargument a id and
            set its commandname as abc and set text with the value that will come inside the
            Login_status columnit can be
             --%>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton2" runat="server"
                        CommandArgument='<%#Eval("id") %>' CommandName="abc"
                        Text='<%# Eval("Login_status") %>'></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Password">
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Eval("Password") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Retype_password" >
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Eval("Retype_password") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="delete">
              <%--here am placing the link button and set its commandargument a id and
            set its commandname as del
             --%>
                <ItemTemplate>
               
                    <asp:LinkButton ID="LinkButton3" runat="server"
                        CommandArgument='<%# Eval("id") %>' CommandName="del"
                       
                        onclientclick="confirm return('Are you sure want to delete the current record')">delete</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#7C6F57" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    <br />
    </form>
</body>
</html>
Code for aspx.cs page:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    // here i am declaring some object for datatable,SqlConnection,SqlDataAdapter
    SqlConnection con = new SqlConnection();
    SqlDataAdapter adp;
    DataTable dt;
    SqlCommand cmd = new SqlCommand();


    protected void Page_Load(object sender, EventArgs e)
    {
        //  here i am declaring  connectionstring
            con.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
            con.Open();
            //  here i am open the connection if the connection is closed
           if (con.State == ConnectionState.Closed)
          {
            con.Open();
          }
            con.Close();
         if (IsPostBack == false)
          {
              // here i am calling the function that will bind the gridview
            grd_data();
          }
    }

    private void grd_data()
    {
        // this function will bind the gridview dynamically
         if (con.State == ConnectionState.Closed)
          {
            con.Open();
          }
            adp = new SqlDataAdapter("select * from tb_user order by id asc",con);
            dt = new DataTable();
            // here i m filling the dt with the values those will come inside the SqlDataAdapter adp
            adp.Fill(dt);
            adp.Dispose();
            // here i am checking the rows those will come inside the dt
            GridView1.DataSource = dt;
            GridView1.DataBind();
            con.Close();
    }


    protected void Button1_Click(object sender, EventArgs e)
    {
          // this code is used to insert the value inside the table
          //  here i am open the connection if the connection is closed
          if (con.State == ConnectionState.Closed)
          {
            con.Open();
          }
         // here m declaring the sql query to inser the values
            cmd.CommandText = "insert into tb_user values(@name,@age,default,@password,@retype_password)";
            cmd.Connection = con;
            // below m declaring the parameters for this insert query
           
            cmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = txt_name.Text;
            cmd.Parameters.Add("@age", txt_age.Text);
            cmd.Parameters.Add("@password", SqlDbType.VarChar, 50).Value = txt_pswrd.Text;
            cmd.Parameters.Add("@retype_password", SqlDbType.VarChar, 50).Value = txt_repswrd.Text;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            txt_name.Text = "";
            txt_age.Text = "";
           
            txt_pswrd.Text = "";
            txt_repswrd.Text = "";
            con.Close();
        // here m calling the function named grd_bind after insertion  this function will call
        // and  display the data with the new row that will insert presently
            grd_data();
    }
   
   
    //GridView-properties-(Events)-Rowcommand-doubleor  click
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        // this code for  Rowcommand event
            Int32 i;
            // inside the i variable m putting the id that will come inside the CommandArgument
            //inside the source code m binding the CommandArgument with the id
            i = Convert.ToInt32(e.CommandArgument);
        if (con.State == ConnectionState.Closed)
          {
            con.Open();
          }
        // here m checking the commandname of the linkbutton.

        if (e.CommandName == "abc")
       {
            // if the commandname will abc then this condition will work
           // here m selecting the login_status correspondence of this id
            adp = new SqlDataAdapter("select login_status from tb_user where id=@id", con);
            adp.SelectCommand.Parameters.AddWithValue("@id", i);
            dt = new DataTable();
            adp.Fill(dt);
            adp.Dispose();

            if (dt.Rows[0]["login_status"].ToString() == "No")
          {
              // if the login_status will no then this condition will works
              // and here m updating the the login_status with the value yes
              //
            cmd = new SqlCommand("update tb_user set login_status=@login_status where id=@id", con);
            cmd.Parameters.AddWithValue("@login_status", "Yes");
            cmd.Parameters.AddWithValue("@id", i);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
          }
            else
          {
              // if the login_status will yes then this condition will works
              // and here m updating the the login_status with the value No
            cmd = new SqlCommand("update tb_user set login_status=@login_status where id=@id", con);
            cmd.Parameters.AddWithValue("@login_status", "No");
            cmd.Parameters.AddWithValue("@id", i);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
          }
          
       }
        // here m checking the commandname of the linkbutton.
            if (e.CommandName == "del")
            {
                // if the commandname will abc then this condition will work
                // here m deleting the data from the column correspondence of this id
                cmd = new SqlCommand("delete from tb_user where id=@id", con);
                cmd.Parameters.AddWithValue("@id", i);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
            }


            grd_data();
            con.Close();

    }
}
See output in this image:
See inside the gridview, login_status column.  You can change the status after pressing the no. it changes no to yes ans yes to no






Sql Script for database:
/****** Object:  Default [DF_tb_user_Login_status]    Script Date: 12/04/2011 10:49:24 ******/
IF  EXISTS (SELECT * FROM sys.default_constraints WHERE object_id = OBJECT_ID(N'[dbo].[DF_tb_user_Login_status]') AND parent_object_id = OBJECT_ID(N'[dbo].[tb_user]'))
Begin
ALTER TABLE [dbo].[tb_user] DROP CONSTRAINT [DF_tb_user_Login_status]

End
GO
/****** Object:  Table [dbo].[tb_user]    Script Date: 12/04/2011 10:49:24 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_user]') AND type in (N'U'))
DROP TABLE [dbo].[tb_user]
GO
/****** Object:  Table [dbo].[tb_user]    Script Date: 12/04/2011 10:49:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_user]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tb_user](
      [id] [int] IDENTITY(1,1) NOT NULL,
      [Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [Age] [int] NULL,
      [Login_status] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [Password] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
      [Retype_password] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
 CONSTRAINT [PK_tb_user] PRIMARY KEY CLUSTERED
(
      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
)
END
GO
SET IDENTITY_INSERT [dbo].[tb_user] ON
INSERT [dbo].[tb_user] ([id], [Name], [Age], [Login_status], [Password], [Retype_password]) VALUES (2, N'vikram', 30, N'Yes', N'vikram', N'vikram')
INSERT [dbo].[tb_user] ([id], [Name], [Age], [Login_status], [Password], [Retype_password]) VALUES (3, N'Bharat', 23, N'No', N'bharat', N'bharat')
SET IDENTITY_INSERT [dbo].[tb_user] OFF
/****** Object:  Default [DF_tb_user_Login_status]    Script Date: 12/04/2011 10:49:24 ******/
IF Not EXISTS (SELECT * FROM sys.default_constraints WHERE object_id = OBJECT_ID(N'[dbo].[DF_tb_user_Login_status]') AND parent_object_id = OBJECT_ID(N'[dbo].[tb_user]'))
Begin
ALTER TABLE [dbo].[tb_user] ADD  CONSTRAINT [DF_tb_user_Login_status]  DEFAULT ('No') FOR [Login_status]

End
GO
Conclusion
Through this article, you have learned how to work  rowcommand event inside the gridview.