Friday 25 April 2014

Bind Data to DDL with RowDataBound and SelectedIndexChanged in VB.NET

Ans:-
Here i have taken one GridView and in Gridview i have taken DropDownList.
Now i have to bind/get data from DB in to DropDownList. And then while selecting DDL, indexchanged event will generate and according to that value Gridview row value will be change.

See the below is UI of small application..
1.

2.


3.


DDlSelectedIndexChangedInGv.aspx:-

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DDlSelectedIndexChangedInGv.aspx.vb" Inherits="DDlSelectedIndexChangedInGv" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>DDl in SelectedIndexChanged in GridView Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            PageSize="1" AllowPaging="true" >
            <Columns>
                <asp:TemplateField HeaderText="Select" SortExpression="id">
                 
                    <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
                            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
               <%-- <asp:BoundField DataField="id" HeaderText="id" SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField DataField="descrptn" HeaderText="descrptn"
                    SortExpression="descrptn" />--%>
                   
                    <asp:TemplateField HeaderText="id"
                    SortExpression="id">
                    <ItemTemplate>
                        <asp:Label ID="lblId" runat="server" Text='<%# Bind("id") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtId" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="name" SortExpression="name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="desc" SortExpression="descrptn">
                    <ItemTemplate>
                        <asp:Label ID="lblDesc" runat="server" Text='<%# Bind("descrptn") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtDesc" runat="server" Text='<%# Bind("descrptn") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </center>
    </form>
</body>
</html>

DDlSelectedIndexChangedInGv.aspx.vb:-

Imports System
Imports System.Data
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Partial Class DDlSelectedIndexChangedInGv
    Inherits System.Web.UI.Page
    Dim obj As New Class1
    Dim cn As SqlConnection
    Dim cmd As SqlCommand
    Dim da As SqlDataAdapter
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindData()
        End If
    End Sub
    Private Sub BindData()
        cn = New SqlConnection(obj.GetConnection())
        cn.Open()
        cmd = New SqlCommand("select * from test", cn)
        da = New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds)
        cn.Close()
        GridView1.DataSource = ds
        GridView1.DataBind()
    End Sub

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            cn = New SqlConnection(obj.GetConnection())
            cn.Open()
            Dim ddl As DropDownList = DirectCast(e.Row.FindControl("DropDownList1"), DropDownList)
            'Dim id As Integer = Convert.ToInt32(e.Row.Cells(1).Text)              'it returns value from gridview databound field
            cmd = New SqlCommand("select * from test", cn)
            da = New SqlDataAdapter(cmd)
            Dim ds As New DataSet
            da.Fill(ds)
            cn.Close()
            ddl.DataSource = ds
            ddl.DataTextField = "id"
            ddl.DataValueField = "id"
            ddl.DataBind()
            ddl.Items.Insert(0, New ListItem("-Select-", "0"))
        End If
    End Sub

    Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        cn = New SqlConnection(obj.GetConnection())
        cn.Open()
        
        Dim ddl As DropDownList = DirectCast(sender, DropDownList)
        Dim id As Integer = Convert.ToInt32(ddl.SelectedValue)
        cmd = New SqlCommand("select * from test where id=" & id, cn)

        da = New SqlDataAdapter(cmd)
        Dim dt As New DataTable
        da.Fill(dt)
        cn.Close()

        Dim ddlist As New DropDownList
        Dim lbId As Label
        Dim lbName As Label
        Dim lbDesc As Label

        If dt.Rows.Count > 0 Then
            Dim i As Integer = 0
            For i = 0 To dt.Rows.Count - 1
                ddlist = GridView1.Rows(i).FindControl("DropDownList1")
                lbId = GridView1.Rows(i).FindControl("lblId")
                lbName = GridView1.Rows(i).FindControl("lblName")
                lbDesc = GridView1.Rows(i).FindControl("lblDesc")

                If ddlist.SelectedIndex > 0 Then
                    lbId.Text = dt.Rows(i)("id").ToString()
                    lbName.Text = dt.Rows(i)("name").ToString()
                    lbDesc.Text = dt.Rows(i)("descrptn").ToString()
                End If
            Next
        End If
    End Sub

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        BindData()
    End Sub
End Class

Class1.vb:-

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient

Public Class Class1
    Dim sqlcmd As SqlCommand
    Dim sqldr As SqlDataReader
    Public Function GetConnection() As String
        Dim conStr As String = "Server=192.168.0.200;database=SubsDB;UID=sa;Password=amtpl@123;Pooling=true;Min Pool Size=2;Max Pool Size=1000"
        Return conStr
    End Function
    Public Sub AddCombo(ByVal CntName As DropDownList, ByVal SqlStr As String, ByVal sCon As SqlConnection)
        'Which will fill the DropdownList Based on Query
        Try
            CntName.Items.Clear()
            CntName.Items.Add("")
            sqlcmd = New SqlCommand(SqlStr, sCon)
            sqldr = sqlcmd.ExecuteReader()
            While sqldr.Read
                CntName.Items.Add(sqldr(0))
            End While
            sqldr.Close() : sqlcmd.Dispose()
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
    End Sub
End Class

Create Table:-
create table test(id int primary key,name varchar(30),descrptn varchar(30))


Search Result through TelerikRadComboBox in VB.NET

Ans:-
Here i have taken two TelerikRadComboBox,one is state and another is city. While search any letter or word,if that is available in DB that will show in state RadComboBox.And then according  to state,we can get city.

See in Below Pics for better understanding..

1.


2.


3.


4.


5.



SearchOnTelerikComboBox.aspx:-

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="SearchOnTelerikComboBox.aspx.vb" Inherits="DDlwthTelerikComboBox" %>

<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>DDlwthTelerikComboBox Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <center>
    <div>
     <table>
    <tr>
    <td>
    <asp:Label ID="Label34" runat="server" Text="State" Width="118px" Style="color: Maroon;
                                                        font-family: Verdana; font-size: 8pt"></asp:Label>
    </td>
     <td>
                                                    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                                                        <ContentTemplate>
                                                           <%-- <asp:DropDownList ID="ddlState1" runat="server" Width="1px" Enabled="False" TabIndex="41"
                                                                AutoPostBack="True" Height="22px" Font-Names="Verdana" Font-Size="8.5pt" Visible="False">
                                                            </asp:DropDownList>--%>
                                                            <telerik:RadComboBox ID="ddlState" runat="server" EnableViewState="false" EmptyMessage="Select a State"
                                                                EnableLoadOnDemand="True" AllowCustomText="True" MarkFirstMatch="True" Style="color: Black;
                                                                background-color: White; font-family: Verdana; font-size: 8.5pt;" TabIndex="43"
                                                                AutoPostBack="True" Width="240px" Skin="Sunset" DropDownCssClass="RadComboBox_Sunset"
                                                                EnableEmbeddedSkins="False" BorderColor="#999999" BorderStyle="Solid" EnableVirtualScrolling="True"
                                                                BorderWidth="1px" ShowMoreResultsBox="True">
                                                            </telerik:RadComboBox>
                                                            <span style="font-size: 8pt; color: maroon">*</span>
                                                        </ContentTemplate>
                                                    </asp:UpdatePanel>
                                                </td>
                                                </tr>
                                                <tr>
                                                <td>
                                                <asp:Label ID="Label1" runat="server" Text="City" Width="118px" Style="color: Maroon;
                                                        font-family: Verdana; font-size: 8pt"></asp:Label>
                                                </td>
                                                <td>
                                                 <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                                                        <ContentTemplate>
                                                           <%-- <asp:DropDownList ID="ddlCity1" runat="server" Width="1px" AutoPostBack="True" TabIndex="42"
                                                                Font-Size="8.5pt" Height="22px" Enabled="False" Font-Names="Verdana" Visible="False">
                                                            </asp:DropDownList>--%>
                                                            <telerik:RadComboBox ID="ddlCity" runat="server" EnableViewState="false" EmptyMessage="Select a City"
                                                                EnableLoadOnDemand="True" AllowCustomText="True" MarkFirstMatch="True" Style="color: Black;
                                                                background-color: White; font-family: Verdana; font-size: 8.5pt;" TabIndex="44"
                                                                Width="240px" AutoPostBack="True" Skin="Sunset" DropDownCssClass="RadComboBox_Sunset"
                                                                EnableEmbeddedSkins="False" BorderColor="#999999" BorderStyle="Solid" EnableVirtualScrolling="True"
                                                                BorderWidth="1px" ShowMoreResultsBox="True">
                                                            </telerik:RadComboBox>
                                                            <span style="font-size: 8pt; color: maroon">*</span>
                                                        </ContentTemplate>
                                                    </asp:UpdatePanel>
                                                </td>
                                                </tr>                                              
                                                <tr>
                                                <td>
                                                &nbsp;
                                                </td>
                                                </tr>
                                                <tr>
                                                <td>
                                                <%--<asp:ImageButton ID="btnAdd" runat="server" AccessKey="A" ImageUrl="~/Images/Add.gif"
                                                                    TabIndex="52" ToolTip="Alt+a" />--%>
                                                </td>
                                                </tr>
    <tr>
    <td>
    <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
    </td>
        </tr>
    </table>
    </div>
    </center>
    </form>
</body>
</html>

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Telerik.Web.UI
Partial Class DDlwthTelerikComboBox
    Inherits System.Web.UI.Page
    Dim obj As New Class1
    Dim cn As SqlConnection
    Dim cmd As SqlCommand
    Dim da As SqlDataAdapter
    Dim dt As New DataTable
    Dim ds As New DataSet
    Dim spStr() As String
    Dim sFlag As Integer = 0

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            cn = New SqlConnection(obj.GetConnection()) : cn.Open()

        Catch ex As Exception
            lblMsg.Text = ex.Message
        End Try

    End Sub
    Protected Sub ddlState_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles ddlState.ItemsRequested
        Try
            da = New SqlDataAdapter("Select distinct ltrim(rtrim(cast(sid as varchar)))+'-'+ltrim(rtrim(sname)) State from state where sname LIKE '" + e.Text + "%'", cn)
            da.Fill(dt)
            Dim itemsPerRequest As Integer = 20
            Dim itemOffset As Integer = e.NumberOfItems
            Dim endOffset As Integer = itemOffset + itemsPerRequest
            If endOffset > dt.Rows.Count Then
                endOffset = dt.Rows.Count
            End If
            Dim i As Integer = itemOffset
            While i < endOffset
                spStr = Split(dt.Rows(i)("State").ToString(), "-")
                ddlState.Items.Add(New RadComboBoxItem(dt.Rows(i)("State").ToString()))
                i = i + 1
            End While
            If dt.Rows.Count > 0 Then
                e.Message = [String].Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", endOffset.ToString(), dt.Rows.Count.ToString())
            Else
                e.Message = "No matches"
            End If

        Catch ex As Exception
            lblMsg.Text = ex.Message
        End Try
    End Sub
    Protected Sub ddlState_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs) Handles ddlState.SelectedIndexChanged
        If ddlState.Text <> "" Then
            Dim r As Integer = obj.FetchValue("select Count(*) from state where ltrim(rtrim(cast(sid as varchar)))+'-'+ltrim(rtrim(sname))='" + ddlState.Text + "'", cn)
            If r = 0 Then
                ddlState.Focus()
                'MsgBox("State not Found", MsgBoxStyle.OkOnly)
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('State Not Found...');", True)
                ddlState.Text = "" : ScriptManager1.SetFocus(ddlState.ClientID + "_Input") : sFlag = 1 : Exit Sub
            Else
                ddlCity.Text = ""
                ScriptManager1.SetFocus(ddlCity.ClientID + "_Input")
            End If
        End If
    End Sub

SearchOnTelerikComboBox.aspx.vb:-
   
    Protected Sub ddlCity_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles ddlCity.ItemsRequested
        Try
            If ddlState.Text <> "" Then
                spStr = Split(ddlState.Text, "-")
                da = New SqlDataAdapter("select distinct ltrim(rtrim(cast(c.cid as varchar)))+'-'+ltrim(rtrim(c.cname)) City from city c,[state] s where c.sid='" + spStr(0) + "' and c.cname LIKE '" + e.Text + "%'", cn)
                da.Fill(dt)
                Dim itemsPerRequest As Integer = 20
                Dim itemOffset As Integer = e.NumberOfItems
                Dim endOffset As Integer = itemOffset + itemsPerRequest
                If endOffset > dt.Rows.Count Then
                    endOffset = dt.Rows.Count
                End If
                Dim i As Integer = itemOffset
                While i < endOffset
                    spStr = Split(dt.Rows(i)("City").ToString(), "-")
                    ddlCity.Items.Add(New RadComboBoxItem(dt.Rows(i)("City").ToString()))
                    i = i + 1
                End While
                If dt.Rows.Count > 0 Then
                    e.Message = [String].Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", endOffset.ToString(), dt.Rows.Count.ToString())
                Else
                    e.Message = "No matches"
                End If
            End If
        Catch ex As Exception
            lblMsg.Text = ex.Message
        End Try
    End Sub
    Protected Sub ddlCity_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs) Handles ddlCity.SelectedIndexChanged
        If ddlCity.Text <> "" Then
            Dim r As Integer = obj.FetchValue("select Count(*) from city where ltrim(rtrim(cast(cid as varchar)))+'-'+ltrim(rtrim(cname))='" + ddlCity.Text + "'", cn)
            If r = 0 Then
                ddlCity.Focus()
                'MsgBox("State not Found", MsgBoxStyle.OkOnly)
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('City Not Found...');", True)
                ddlState.Text = "" : ScriptManager1.SetFocus(ddlState.ClientID + "_Input") : sFlag = 1 : Exit Sub
            End If
        End If
    End Sub

    'Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAdd.Click
    '    Try
    '        obj.AddComboTi(ddlState, "select ltrim(rtrim(cast(sid as varchar)))+'-'+ltrim(rtrim(sname)) from state", cn)

    '    Catch ex As Exception
    '        lblMsg.Text = ex.Message
    '    End Try
    'End Sub
End Class

Class1.vb:-

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient
Imports Telerik.Web.UI

Public Class Class1
    Dim sqlcmd As SqlCommand
    Dim sqldr As SqlDataReader
    Public Function GetConnection() As String
        Dim conStr As String = "Server=192.168.0.200;database=SubsDB;UID=sa;Password=amtpl@123;Pooling=true;Min Pool Size=2;Max Pool Size=1000"
        Return conStr
    End Function
    Public Sub AddCombo(ByVal CntName As DropDownList, ByVal SqlStr As String, ByVal sCon As SqlConnection)
        'Which will fill the DropdownList Based on Query
        Try
            CntName.Items.Clear()
            CntName.Items.Add("")
            sqlcmd = New SqlCommand(SqlStr, sCon)
            sqldr = sqlcmd.ExecuteReader()
            While sqldr.Read
                CntName.Items.Add(sqldr(0))
            End While
            sqldr.Close() : sqlcmd.Dispose()
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
    End Sub
    Public Sub AddComboTi(ByVal CntName As RadComboBox, ByVal SqlStr As String, ByVal sCon As SqlConnection)
        'Which will fill the DropdownList Based on Query
        Try
            CntName.Items.Clear()
            'Dim Str As String = String.Empty
            ' CntName.Items.Add(New RadComboBoxItem(""))
            sqlcmd = New SqlCommand(SqlStr, sCon)
            sqldr = sqlcmd.ExecuteReader()
            While sqldr.Read
                CntName.Items.Add(New RadComboBoxItem(sqldr(0)))
            End While
            sqldr.Close() : sqlcmd.Dispose()
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
    End Sub
    Public Function FetchValue(ByVal qStr As String, ByVal sCon As SqlConnection) As String
        'Which will give the Find Value Based on Query
        Try
            Dim sqlFetch = New SqlCommand(qStr, sCon)
            FetchValue = sqlFetch.ExecuteScalar()
            sqlFetch.Dispose()
        Catch ex As Exception
            FetchValue = ""
        End Try
    End Function

End Class

Create Table:-

create table state(sid int constraint p1 primary key,sname varchar(30))
create table city(cid int primary key,cname varchar(30),sid int constraint f1 foreign key references state(sid))

Monday 21 April 2014

Get/Bind Data in DropDownList within Gridview in VB.NET

Ans:-
Here i have taken one GridView and in Gridview i have taken DropDownList.
Now i have to bind/get data from DB in to DropDownList which is placed in Gridview.

See the below is UI of small application..


DDLInGrdView.aspx:-

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DDLInGrdView.aspx.vb" Inherits="DDLInGrdView" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>DDL in GridView Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <div>
 
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="sid" HeaderText="sid" SortExpression="sid" />
                <asp:BoundField DataField="sname" HeaderText="sname" SortExpression="sname" />
               
                <asp:TemplateField HeaderText="city" SortExpression="sid">
                   <ItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server"  ></asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
   
    </div>
    <div>
        <asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
    </div>
    </center>
    </form>
</body>
</html>

DDLInGrdView.aspx.vb:-

Imports System
Imports System.Data
Imports System.Web.UI.WebControls
Imports System.Data.SqlClient
Partial Class DDLInGrdView
    Inherits System.Web.UI.Page
    Dim obj As New Class1
    Dim cn As SqlConnection
    Dim cmd As SqlCommand
    Dim da As SqlDataAdapter
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindData()
        End If
    End Sub

    Private Sub BindData()
        cn = New SqlConnection(obj.GetConnection())
        cn.Open()
        cmd = New SqlCommand("select * from state", cn)
        da = New SqlDataAdapter(cmd)
        Dim ds As New DataSet()
        da.Fill(ds)
        cn.Close()
        GridView1.DataSource = ds
        GridView1.DataBind()
    End Sub
   
    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then
            cn = New SqlConnection(obj.GetConnection())
            cn.Open()
            Dim ddl As DropDownList = DirectCast(e.Row.FindControl("DropDownList1"), DropDownList)
            Dim sid As Integer = Convert.ToInt32(e.Row.Cells(0).Text)
            cmd = New SqlCommand("select * from city where sid=" & sid, cn)
            da = New SqlDataAdapter(cmd)
            Dim ds As New DataSet
            da.Fill(ds)
            cn.Close()
            ddl.DataSource = ds
            ddl.DataTextField = "cname"
            ddl.DataValueField = "cname"
            ddl.DataBind()
            ddl.Items.Insert(0, New ListItem("-Select-", "0"))
        End If
    End Sub

End Class

In Class1.vb:-

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient

Public Class Class1
    Dim sqlcmd As SqlCommand
    Dim sqldr As SqlDataReader
    Public Function GetConnection() As String
        Dim conStr As String = "Server=.;database=SubsDB;UID=sa;Password=123;Pooling=true;Min Pool Size=2;Max Pool Size=1000"
        Return conStr
    End Function
End Class

Create Table:-

create table state(sid int primary key,sname varchar(30))
create table city(cid int primary key,cname varchar(30),sid int foreign key references state(sid))

Delete Duplicate Records/Rows from Table in Sql Server

Ans:-

use SubsDB
create table test(id int,name varchar(30),descrptn varchar(30))

--1.(it contain duplicate records)
select * from test
--here this table(test1) only keep unique records
select distinct * into test1 from test
--here drop the table test
drop table test
--here rename the table test1 to test
sp_rename test1,test

OR
--2.(it contain duplicate records)
select * from test
--here this table(test1) only keep unique records
select distinct * into test1 from test
select * from test1
--here delete all the records of table(test) test
truncate table test
select * from test
--here insert one whole table(test1) records into another table(test)
insert into test select * from test1
select * from test
-- then we can drop the table(test1)
drop table test1

OR
insert into test select * from test
--3.(it contain duplicate records)
select * from test
--select whole query given below and exucute,we will get unique records
with cte as(select id,name,descrptn,RN = ROW_NUMBER()OVER(PARTITION BY id ORDER BY id) FROM test
)

DELETE FROM CTE WHERE RN > 1

Wednesday 16 April 2014

Show All Data and Get Single Record from DB using Gridview & DropDownList in ASP.NET

Ans:-
1.Here i have taken one Gridview to show all the records of user from DB.
2.and then taken one DropDownList and another Grodview to show the paricular user records from DB while selecting the DropDownList.

See Below Snaps of UI..


Default.aspx:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>User Provider Policy Plan Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <div>
    <b>Get All User Details:</b>
    <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    <br />
    <div>
    <b>Get User Details By ID:</b>
    <br />
        <asp:TextBox ID="txtUserID" runat="server"></asp:TextBox>
        &nbsp;
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" />
        <br />
    <asp:GridView ID="GridView2" runat="server">
        </asp:GridView>
    </div>
    <div>
     <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
    </div>
    </center>
    </form>
</body>
</html>

Default.aspx.cs:-

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 
{
    Class1 obj_Class1 = new Class1();
    SqlConnection cn;
    SqlDataAdapter da;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetUserDetails();
        }
    }
    void GetUserDetails()
    {
        cn = new SqlConnection(obj_Class1.GetConnection());
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spGetUserDetails";
        da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        cn = new SqlConnection(obj_Class1.GetConnection());
        cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spGetUserDetailsByID";
        cmd.Parameters.Add("@UserID", SqlDbType.Int).Value=txtUserID.Text;
        da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        try
        {
            cn.Open();
            da.Fill(dt);    
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
        finally
        {
            cn.Close();
        }
        GridView2.DataSource = dt;
        GridView2.DataBind();
    }
}

Class1.cs:-

using System;
using System.Data;
using System.Configuration;
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;

/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
public Class1()
{
//
// TODO: Add constructor logic here
//
}
    public string GetConnection()
    {
        string strCon = "server=.;database=subsdb;user id=sa;pwd=123";
        return strCon;
    }
}

Tables & SP's;-

create table tbluser(uid int constraint p primary key,uname varchar(30))

create table tblprovider(providerid int constraint p1 primary key,providername varchar(30),uid int constraint f11 foreign key references tbluser(uid)on delete cascade on update cascade)

create table tblpolicy(policyid int constraint p2 primary key,policyname varchar(30),uid int constraint f12 foreign key references tbluser(uid)on delete cascade on update cascade)

create table tblplan(planid int constraint p3 primary key,planname varchar(30),uid int constraint f13 foreign key references tbluser(uid)on delete cascade on update cascade)

insert into tbluser values(2,'pravin')
insert into tblprovider values(103,'eye hospital',2)
insert into tblpolicy values(1003,'policy3',2)
insert into tblplan values(10003,'plan3',2)
insert into tblplan(policyid) values(1001)

--for add column & datatype to the table
alter table tblpolicy
add providerid int

-- add foreign key to the already existing column
alter table tblpolicy
add constraint f15 foreign key(providerid) references tblprovider(providerid)

--for renaming column
sp_rename 'tblprovider.pname','providername'

create proc spGetUserDetails
as
begin
select u.uname,pro.providername,pol.policyname,pl.planname from tbluser u
inner join tblprovider pro on u.uid=pro.uid inner join tblpolicy pol
on u.uid=pol.uid inner join tblplan pl on u.uid=pl.uid
end

alter proc spGetUserDetailsByID(@UserID int)
as
begin
select u.uname,pro.providername,pol.policyname,pl.planname from tbluser u
inner join tblprovider pro on u.uid=pro.uid inner join tblpolicy pol
on u.uid=pol.uid inner join tblplan pl on u.uid=pl.uid where u.uid=@UserID;
end

exec spGetUserDetailsByID 1

Get Data to DropDownList from DB using Class file in VB.NET

Ans:-

Default2.aspx:-

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Get State Data Page</title>
</head>
<body>
    <form id="form1" runat="server">
     <center>
     <div>
    <table>
    <tr>
    <td>
    <asp:HyperLink ID="Hiperlink" runat ="server" NavigateUrl ="~/Default.aspx" Target ="_blank" Text="Go To Default.aspx" ></asp:HyperLink>
    </td>
    </tr>
    <tr>
    <td align="left">
   <asp:Label ID="lblState" runat="server" Text="State Code" Width="115px"></asp:Label>
                                    </td>
                                    <td align="left">
                                     <asp:DropDownList ID="ddlState" runat="server" Width="100px" TabIndex="3">
                                    </asp:DropDownList>
                                    </td>
                                    <td>
                                        <asp:Button ID="Button1" runat="server"
                                            Text="Button" />
                                    </td>
    </tr>
    </table>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </center>
    </form>
</body>
</html>

Default2.aspx.cs:-

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls

Partial Class Default2
    Inherits System.Web.UI.Page
    Dim obj As New Class1
    Dim sqlCon As SqlConnection

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        sqlCon = New SqlConnection(obj.GetConnection())
        sqlCon.Open()
        If Not IsPostBack Then
            ddlState.Items.Add("")
            obj.AddCombo(ddlState, "select CAST(sid as varchar)+'-'+sname as states from state", sqlCon)
            ddlState.Items.Insert(1, "All")
            ddlState.Visible = True

        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = ddlState.SelectedValue
    End Sub
End Class

Class1.cs:-

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient

Public Class Class1
    Dim sqlcmd As SqlCommand
    Dim sqldr As SqlDataReader
    Public Function GetConnection() As String
        Dim conStr As String = "Server=.;database=SubsDB;UID=sa;Password=123;Pooling=true;Min Pool Size=2;Max Pool Size=1000"
        Return conStr
    End Function
    Public Sub AddCombo(ByVal CntName As DropDownList, ByVal SqlStr As String, ByVal sCon As SqlConnection)
        'Which will fill the DropdownList Based on Query
        Try
            CntName.Items.Clear()
            CntName.Items.Add("")
            sqlcmd = New SqlCommand(SqlStr, sCon)
            sqldr = sqlcmd.ExecuteReader()
            While sqldr.Read
                CntName.Items.Add(sqldr(0))
            End While
            sqldr.Close() : sqlcmd.Dispose()
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
    End Sub
End Class

Create Table and Stored Procedure:-

create table state(sid int,sname varchar(30))

Generate Crystal Report and Export Report to Excel in VB.NET

Ans:-
1.Here i have taken one DropDownList,while selecting DDL value and 2. then Clicking the Button(Show Report) Report will Generate and then automatically another Button will visible and 3. then Clicking the Button(Export Report) it will export Report to Excel(.xls).

See Below UI Snaps to better understand..
1.


2.

3.


GetPlanPolicyProviderNm.aspx:-

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="GetPlanPolicyProviderNm.aspx.vb" Inherits="GetPlanPolicyProviderNm" %>

<%@ Register Assembly="CrystalDecisions.Web, Version=10.5.3700.0, Culture=neutral, PublicKeyToken=692fbea5521e1304"
    Namespace="CrystalDecisions.Web" TagPrefix="CR" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Get Plan Policy Provider Name Page</title>
    <script type="text/javascript" language="javascript">
        function validate() {
            var ddl = document.getElementById("DropDownList1")
            if (ddl.selectedIndex == 0) {
                ddl.focus();
                alert("Plz Select UId..");
                return false;
            }
        }
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <center>
    <div>
    <table>
    <tr>
    <td>
    Select Uid :
    </td>
    <td align="left">
     <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </td>
    <td>
       <asp:Button ID="btnShowRpt" runat="server" Text="Show Report" OnClientClick="return validate()" />
    </td>
     </tr>
      <tr>
      <td></td>
      <td></td>
     <td >
     <asp:Button ID="btnExport" runat="server" Text="Export Report" />
     </td>
     </tr>  
     <tr>
     <td colspan="3">
      &nbsp;
     </td>
   
     </tr>
     <tr>
     <td colspan="3">
       
         <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" HasExportButton="True"
             AutoDataBind="true" ReportSourceID="CrystalReportSource1"  Width="901px" Visible="false" />
         <CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
             <Report FileName="CrystalReport.rpt">
             </Report>
             </CR:CrystalReportSource>
     </td>
     </tr>
         </table>
      </div>
    </center>
    </form>
</body>
</html>

GetPlanPolicyProviderNm.aspx.vb:-

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports CrystalDecisions.ReportAppServer.ClientDoc

Partial Class GetPlanPolicyProviderNm
    Inherits System.Web.UI.Page
    Dim cn As SqlConnection
    Dim cmd As SqlCommand
    Dim ds As New DataSet
    Dim da As SqlDataAdapter
    Dim spStr() As String
    Dim obj As New Class1
    Dim store() As Integer
    Dim cryRpt As ReportDocument

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        cn = New SqlConnection(obj.GetConnection())
        cn.Open()
        If Not IsPostBack Then
            DropDownList1.Items.Clear()
            DropDownList1.Items.Add("")
            obj.AddCombo(DropDownList1, "select cast(uid as varchar)+'-'+uname as uname from tbluser", cn)
            DropDownList1.Items.Insert(1, "0-All")

            btnExport.Visible = False
        End If
        'Call ShowReport()
    End Sub
    Private Sub ShowReport()
        Try
            If DropDownList1.SelectedIndex > 0 Then
                cmd = New SqlCommand("spGetPlanPolicyProviderNm", cn)
                cmd.CommandType = CommandType.StoredProcedure

                spStr = Split(DropDownList1.SelectedValue, "-")
                cmd.Parameters.Add(New SqlParameter("@uid", spStr(0)))

                If DropDownList1.Text = "0-All" Then
                    spStr = Split(DropDownList1.Text, "-")
                    cmd.Parameters.Add(New SqlParameter("@allUser", spStr(0)))
                End If

                da = New SqlDataAdapter(cmd)
                cmd.CommandTimeout = 0
                da.Fill(ds, "tb1")

                CrystalReportSource1.ReportDocument.SetDataSource(ds.Tables("tb1"))
                CrystalReportViewer1.Visible = True
                CrystalReportViewer1.ReportSourceID = "CrystalReportSource1"
                CrystalReportViewer1.DataBind()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Protected Sub btnShowRpt_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnShowRpt.Click
        Try
            ShowReport()
            btnExport.Visible = True
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Try
            cmd = New SqlCommand("spGetPlanPolicyProviderNm", cn)
            cmd.CommandType = CommandType.StoredProcedure

            spStr = Split(DropDownList1.SelectedValue, "-")
            cmd.Parameters.Add(New SqlParameter("@uid", spStr(0)))             'get record of one user..

            If DropDownList1.Text = "0-All" Then                               'get record of all users..
                spStr = Split(DropDownList1.Text, "-")
                cmd.Parameters.Add(New SqlParameter("@allUser", spStr(0)))
            End If

            da = New SqlDataAdapter()
            da.SelectCommand = cmd
            Dim datatable As New DataTable
            da.Fill(datatable)                                                  'getting value according to imageID and fill dataset

            Dim crystalReport As New ReportDocument                             'creating object of crystal report
            crystalReport.Load(Server.MapPath("~/CrystalReport.rpt"))           'path of report 
            crystalReport.SetDataSource(datatable)                              'binding datatable
            CrystalReportViewer1.ReportSource = crystalReport

  crystalReport.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.ExcelRecord, Response, True, "UserPolicyDetails")
            'here i have use [ CrystalDecisions.Shared.ExportFormatType.ExcelRecord ] to Export in Excel

   'crystalReport.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, True, "UserPolicyDetails")
            'here i have use[CrystalDecisions.Shared.ExportFormatType.PortableDocFormat ] to Export in PDF

      'crystalReport.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.WordForWindows, Response, True, "UserPolicyDetails")
            'here i have use [ CrystalDecisions.Shared.ExportFormatType.WordForWindows ] to Export in Word

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class

Class1.vb:-

Imports Microsoft.VisualBasic
Imports System.Data.SqlClient

Public Class Class1
    Dim sqlcmd As SqlCommand
    Dim sqldr As SqlDataReader
    Public Function GetConnection() As String
        Dim conStr As String = "Server=.;database=SubsDB;UID=sa;Password=123;Pooling=true;Min Pool Size=2;Max Pool Size=1000"
        Return conStr
    End Function
    Public Sub AddCombo(ByVal CntName As DropDownList, ByVal SqlStr As String, ByVal sCon As SqlConnection)
        'Which will fill the DropdownList Based on Query
        Try
            CntName.Items.Clear()
            CntName.Items.Add("")
            sqlcmd = New SqlCommand(SqlStr, sCon)
            sqldr = sqlcmd.ExecuteReader()
            While sqldr.Read
                CntName.Items.Add(sqldr(0))
            End While
            sqldr.Close() : sqlcmd.Dispose()
        Catch ex As Exception
            'MsgBox(ex.Message)
        End Try
    End Sub
End Class

Table Store Procedure:-

create table tbluser(uid int constraint p primary key,uname varchar(30))

create table tblprovider(providerid int constraint p1 primary key,providername varchar(30),uid int constraint f11 foreign key references tbluser(uid)on delete cascade on update cascade)

create table tblpolicy(policyid int constraint p2 primary key,policyname varchar(30),uid int constraint f12 foreign key references tbluser(uid)on delete cascade on update cascade)

create table tblplan(planid int constraint p3 primary key,planname varchar(30),uid int constraint f13 foreign key references tbluser(uid)on delete cascade on update cascade)

insert into tbluser values(2,'pravin')
insert into tblprovider values(103,'eye hospital',2)
insert into tblpolicy values(1003,'policy3',2)
insert into tblplan values(10003,'plan3',2)
insert into tblplan(policyid) values(1001)

--for add column & datatype to the table
alter table tblpolicy
add providerid int

-- add foreign key to the already existing column
alter table tblpolicy
add constraint f15 foreign key(providerid) references tblprovider(providerid)

--for renaming column
sp_rename 'tblprovider.pname','providername'

alter proc spGetPlanPolicyProviderNm(@uid int,@allUser varchar(15)=null)
as 
begin
if @allUser=0
Begin
select u.uname,pro.providerid,pro.providername,pol.policyid,pol.policyname,pla.planid,pla.planname from tblprovider pro inner join tblpolicy pol on pro.providerid=pol.providerid inner join 
tblplan pla on pol.policyid=pla.policyid inner join tbluser u on pla.uid=u.uid
End
Else
Begin
select u.uname,pro.providerid,pro.providername,pol.policyid,pol.policyname,pla.planid,pla.planname from tblprovider pro inner join tblpolicy pol on pro.providerid=pol.providerid inner join 
tblplan pla on pol.policyid=pla.policyid inner join tbluser u on pla.uid=u.uid  where u.uid=@uid
end
end

exec spGetPlanPolicyProviderNm 1,0

select cast(uid as varchar)+'-'+uname as uname from tbluser