Tuesday, May 29, 2012

How to connect Database and other events in User control



 
   Before started this topic I have already  given a topic on  User Control  for a fundamental idea. Here a question arises if we will take ASP.NET controls then how to connect database and other events of those controls. We know that user control page is same as ASPX page so coding is also same.

 Step: 1

 Create a user table in our database



 Step: 2
 
   Right click on the folder(User Control) in the web site and add new item as 'WebUserControl.ascx'  and  rename as 'Search.ascx'.

  Add the following code in design page

Source Code :-


  <%@ Control Language="C#" AutoEventWireup="true" CodeFile="LedgerDB.ascx.cs" Inherits="UserControl_LedgerDB" %>
<style type="text/css">
    .style1
    {
        width: 100%;
    }
</style>


<table class="style1">
    <tr>
        <td style="text-align: right" width="40%">
            <asp:Label ID="Label1" runat="server" Text="Search"></asp:Label>
        </td>
        <td><asp:DropDownList ID="DDLUser" runat="server"
    onselectedindexchanged="DDLUser_SelectedIndexChanged" AutoPostBack="True">
    </asp:DropDownList>

            &nbsp;</td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
        <td width="60%"><asp:GridView ID="GridView1" runat="server">
</asp:GridView>
            &nbsp;</td>
    </tr>
</table>



C# Code :-



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class UserControl_LedgerDB : System.Web.UI.UserControl
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {

        con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
        DDLedger.Height = m_ImageHeight;

        if(IsPostBack==false )
        {
         
            da = new SqlDataAdapter("select username,userid from users",con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
             DDLUser .DataSource = dt;
             DDLUser .DataTextField = "username";
             DDLUser .DataValueField = "userid";
             DDLUser .DataBind();
        }
    }


    protected void DDLUser_SelectedIndexChanged(object sender, EventArgs e)
    {
        da = new SqlDataAdapter("select * from users where ledgerid='"+  DDLUser .SelectedValue +"'", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        DataTable dt = ds.Tables[0];
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
 
}


Step:3


   After creating this user control right click on the folder(My Project) and add new item as 'Default.aspx'   and  rename as 'MyPage2.aspx'. Then register the user control page in this page as

 <%@ Register TagPrefix="User" TagName="Username" Src="~/UserControl/ Search.ascx" %>
   

   then  add   this  control anywhere in the page as

       < User : Username  ID="username" runat="server" Visible="True"  />

Step:4


Run the page and on selected index change of user we can able to see the details.









Monday, May 28, 2012

Working with user control in asp.net



       A user control is a file we create that contains a set of other ASP.NET controls and code grouped
together to provide common functionality. The user control can then be used on different pages
within a website. Ex: In our website there is more than one registration pages for different purpose but the addresses  like  country, state,city,plot number, street and pin code etc are common in each registration page so at that time it is required.

  Here I am taking a message box which will display whenever I required

 Step: 1

   After create a new website  right click on the website and add a new folder as 'User Control'.This folder will contain all user control if more than one required.
 
   Right click on the folder and add new item as 'WebUserControl.ascx'  and  rename as 'Popup.ascx'. Here I have taken AJAX and some image file of my choice.

  Add the following code in design page

  Source Code :-

   <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PopUp.ascx.cs" Inherits="Website.App_WebControls.App_UserControls.PopUp" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
 <asp:Button runat="server" ID="BtnMessage" Style="display: none" />
    <asp:ModalPopupExtender ID="modalMessage" runat="server" TargetControlID="BtnMessage"
        PopupControlID="PnlMessage" OkControlID="Okbtn" CancelControlID="imgClose" BackgroundCssClass="ModalBackgroundCSS">
    </asp:ModalPopupExtender>
    <asp:Panel runat="Server" ID="PnlMessage" DefaultButton="Okbtn" Style="border: solid 2px #BBBBBB;
        font-family: Arial; width: 325px; height: 150px">
        <table style="width: 100%; border: 0px none;border-collapse:collapse; " cellspacing="-1" cellpadding="-1" >
            <tr style="background-color:Teal; height: 30px; color: White; font-size: 15px;">
                <td colspan="2">
                    <table style="width: 100%;">
                        <tr>
                            <td style="width: 95%">
                                Message from My Project
                            </td>
                            <td>
                                <asp:Image ID="imgClose" runat="server" ImageUrl="../../images/quite.png" />
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr style="background-color: White; height: 90px">
                <td align="right">
                    <asp:Image ID="imgError" runat="server" ImageUrl="~/images/error.jpg" />
                </td>
                <td>
                    <div style="margin-left: 2%; width: 90%; font-size: 13px;">
                        <asp:Label ID="LblModalMessage" runat="server" Text=""></asp:Label></div>
                </td>
            </tr>
            <tr style="height: 30px; background-color: Teal">
                <td colspan="2" align="right">
                    <asp:Button ID="Okbtn" runat="server" Text="OK" Width="90px" Font-Size="13px" CausesValidation="false" />
                </td>
            </tr>
        </table>
    </asp:Panel>

Design View :-



N.B : No need of writing code in PopUp.ascx.cs page

Step: 2


   After creating this user control  right click on the website and add a new folder as 'My Project'.This    folder will contain all aspx pages if more than one required.
 
   Right click on the folder and add new item as 'Default.aspx'   and  rename as 'MyPage1.aspx'. Then register the user control page in this page as

   <%@ Register Src="~/UserControl/PopUp.ascx"  TagName="Pop" TagPrefix="popup" %>
   

   then  add   this  control anywhere in the page as

    <popup:Pop ID="MessagePop" runat="server" Visible="false" /> 


 Step: 3

  After finished the design create a user defined method as

 void Message(string msg)
        {
            ContentPlaceHolder cp = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
            UserControl uc = (UserControl)cp.FindControl("MessagePop");
            if (uc != null)
            {
                Label lb = (Label)uc.FindControl("LblModalMessage");
                lb.Text = msg;
                MessagePop.Visible = true;
                AjaxControlToolkit.ModalPopupExtender modal = (AjaxControlToolkit.ModalPopupExtender)uc.FindControl("modalMessage");
                modal.Show();
            }
        }


    In button click event  or  whenever the message required  just call

    Message("Data Insereted Successfully !");



   



   

             

Friday, May 18, 2012

Autogenerate the field value in stored procedure


   Generally we auto generate a field to identify a uniqueness when we insert  a record into a table in our code(c#,vb) page and it is use full when it is used by a single user.But it creates a major problem when multiple users are using a program which has to auto generate a field in our code page. Because of  depending on user's efficiency at the time of data entry the auto generate code may mismatch or  through error. So it is advisable to generate a number in stores procedure at the time of insert and then should display to user  that your "Transaction number is:P0001

 Table Design :-



Stored Procedure :-

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE PROCEDURE [dbo].[PROC_ADD_POLICY_MST]

(@P_POLICY_PLAN varchar(100),
@P_MONTHS decimal(10,2),
@P_MON_INSTL INT,
@P_CREDIT_VAL INT,
@P_INSTL_AMT INT,
@P_YEAR_PLAN INT,
@P_ACTIVE CHAR(1)=null,@P_PLAN_TYPE CHAR(1)=null,
@P_POLICY_CD varchar(20)=null,@P_RET_VALUE varchar(10) OUTPUT)
AS

declare @p_pcd varchar(20)
set @p_pcd=(select right('0000'+ convert(varchar(20),max(substring(policy_cd,2,4))+1),4)as policy_cd from policy_mst)
select @p_pcd='P'+ @p_pcd
set @
P_RET_VALUE=@p_pcd
INSERT INTO POLICY_MST VALUES(@P_POLICY_PLAN,@P_MONTHS,@P_MON_INSTL,@P_CREDIT_VAL,@P_INSTL_AMT,@P_YEAR_PLAN,@P_ACTIVE,@P_PLAN_TYPE,@P_RET_VALUE)

return 



VB.Net Code


           con.Open()
            cmd = New SqlCommand
            cmd.Connection = con
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "PROC_ADD_POLICY_MST"
            With cmd.Parameters
                .AddWithValue("@P_POLICY_PLAN", Me.TxtPlan.Text)
                .AddWithValue("@P_MONTHS", Me.NmbMonths.Value)
                .AddWithValue("@P_MON_INSTL", Me.NmbMonInstl.Value)
                .AddWithValue("@P_CREDIT_VAL", Me.NmbCreVal.Value)
                .AddWithValue("@P_INSTL_AMT", Me.NmbInstlAmt.Value)
                .AddWithValue("@P_YEAR_PLAN", Me.numYearPlan.Value)
                .AddWithValue("@P_policy_cd", "")

                If ChkActive.Checked = True Then
                    .AddWithValue("@P_ACTIVE", "Y")
                Else
                    .AddWithValue("@P_ACTIVE", "N")
                End If
                If CmbPlanType.Text = "FD" Then
                    .AddWithValue("@P_PLAN_TYPE", "F")
                ElseIf CmbPlanType.Text = "RD" Then
                    .AddWithValue("@P_PLAN_TYPE", "R")
                Else
                    .AddWithValue("@P_PLAN_TYPE", "M")
                End If
            End With

            cmd.Parameters.Add("@P_RET_VALUE", SqlDbType.VarChar, 50).Direction = ParameterDirection.Output                  cmd.ExecuteNonQuery()  
             con.Close()
            MessageBox.Show("Record Saved and Your Transaction number is:" &
Convert.ToString(cmd.Parameters("@p_ret_value").Value))







Wednesday, May 16, 2012

Getting selected row data from gridview in multiple way


 It is common requirement when we work in a single page means when our input parameters and display records from database in a gridview and we have to get data from selected row to manipulate.

 Table Design






Design View (Source code)


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FrmGetGridViewValue.aspx.cs" Inherits="FrmGetGridViewValue" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
    .style1
    {
        width: 100%;
    }
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">

    <table class="style1">
    <tr>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                onselectedindexchanged="GridView1_SelectedIndexChanged"
                onrowcommand="GridView1_RowCommand">
                <Columns>
               
                    <asp:BoundField DataField="id" HeaderText="ID" />
                    <asp:BoundField DataField="name" HeaderText="Name" />
                   <asp:CommandField ShowSelectButton="True" HeaderText="CommandField"/>
                    <asp:TemplateField HeaderText="LinkButton">
                        <ItemTemplate>
                            <asp:LinkButton ID="LnkSelect" runat="server" CommandName="link">Select</asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </td>
    </tr>
     <tr>
        <td>
            <asp:Label ID="Label1" runat="server" Text="ID"></asp:Label>
            &nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;              <asp:TextBox ID="txtid" runat="server"></asp:TextBox>
         </td>
    </tr>
     <tr>
        <td>
            <asp:Label ID="Label2" runat="server" Text="Name"></asp:Label>
            &nbsp;<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
         </td>
    </tr>
</table>

</asp:Content>








C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class FrmGetGridViewValue : System.Web.UI.Page
{
    SqlConnection con;
    SqlDataAdapter da;
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
            string x = "select * from st1";
            da = new SqlDataAdapter(x,con);
            ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtid.Text = GridView1.SelectedRow.Cells[0].Text;
        txtname.Text = GridView1.SelectedRow.Cells[1].Text;
    }
  
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "link")
        {

            GridViewRow val = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
            int RowIndex = val.RowIndex;

            txtid.Text = GridView1.Rows[RowIndex].Cells[0].Text;
            txtname.Text = GridView1.Rows[RowIndex].Cells[1].Text;
        }
    }
}