Saturday, February 6, 2016

Bind More than One Dropdownlist from DataBase using SqlDataReader

In this article I am going to explain how to bind multiple drop down list from single sqldatareader.

First I have created two table and one procedure. Run given below script in your Sql Server.


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sha_Country]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Sha_Country](
                [CountryId] [int] IDENTITY(1,1) NOT NULL,
                [CountryName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Sha_Country] ON
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (1, N'Afghanistan')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (2, N'Brazil')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (3, N'Cuba')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (4, N'Egypt')
INSERT [dbo].[Sha_Country] ([CountryId], [CountryName]) VALUES (5, N'India')
SET IDENTITY_INSERT [dbo].[Sha_Country] OFF


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Sha_Services]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[Sha_Services](
                [ServiceID] [int] IDENTITY(1,1) NOT NULL,
                [ServiceName] [varchar](30) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
END
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Sha_Services] ON
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (1, N'Service1')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (2, N'Service2')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (3, N'Service3')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (4, N'Service4')
INSERT [dbo].[Sha_Services] ([ServiceID], [ServiceName]) VALUES (5, N'Service5')
SET IDENTITY_INSERT [dbo].[Sha_Services] OFF

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sha_GettwoList]') AND type in (N'P', N'PC'))
BEGIN
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author:                              Sharad Gupta
-- Create date: 6-Jan-2015
-- Description:      
-- =============================================
CREATE PROCEDURE [dbo].[sha_GettwoList]
AS
BEGIN
                -- SET NOCOUNT ON added to prevent extra result sets from
                -- interfering with SELECT statements.
                SET NOCOUNT ON;
 
                SELECT ServiceID,
                                ServiceName
                FROM sha_services
 
                SELECT CountryId,
                                CountryName
                FROM Sha_Country
END
'
END
GO

Now Here code for c# to bind two dropdown list from single SqlDataReader using NextResult() method.

 C# code

using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class DropDown : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetDropDownValues();
        }
    }
    private void GetDropDownValues()
    {
        SqlConnection con = new SqlConnection("data source=.;Database=test;uid=********;pwd=********");
        con.Open();
        SqlCommand cmd = new SqlCommand("sha_GettwoList", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows)// it is not necessity to check it returen true or false || true if one or more row otherwise false
        {
            ddlService.DataSource = dr;
            ddlService.DataTextField = "ServiceName";
            ddlService.DataValueField = "ServiceID";
            ddlService.DataBind();
            ddlService.Items.Insert(0, new ListItem("Select Services", "0"));
            dr.NextResult();// for next select statement
            if (dr.HasRows)
            {
                ddlCountry.DataSource = dr;
                ddlCountry.DataTextField = "CountryName";
                ddlCountry.DataValueField = "CountryId";
                ddlCountry.DataBind();
                ddlCountry.Items.Insert(0, new ListItem("Select Country", "0"));
            }
            else {
                ddlCountry.Items.Insert(0, new ListItem("Country Not Found", "0"));
            }
        }
        else{
            ddlService.Items.Insert(0, new ListItem("Services Not Found", "0"));
        }
    }
}

Source Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DropDown.aspx.cs" Inherits="DropDown" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <fieldSet>
    <legend>Multi DropDown List</legend>
    <table>
    <tr>
    <td>Services:</td>
    <td><asp:DropDownList ID="ddlService" runat="server"></asp:DropDownList> </td>
    </tr>
    <tr>
    <td>Country:</td>
    <td><asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList> </td>
    </tr>
    </table>
    </fieldSet>
    </div>
    </form>
</body>
</html>


OutPut:


Monday, February 1, 2016

When we use Server.Transfer

Most of developer confused with "Server.Transfer" and "Response.Redirect", when we use this one and when we use that one. I think you all have to read the difference between "Server.Transfer" and "Response.Redirect".
  • The "Response.Redirect " makes the round trip and "Server.Transfer" does not.
I think we all know what round trip does, but here, I explain little bit of  the round trip

I explain it by taking an example

Suppose you have one button in your "aspx" page, when you click on that button your page is post back, the button click event will be fired, basically browser send request to the server and server processes that request and then send back to browser.

(Note:  The Web applications use HTTP to build up communication between the Web browser and the Web server. HTTP is disconnected in nature, which implies that the life cycle of a Web page is only a single roundtrip. Each time a Web server reacts to a page demand, it crisply makes the assets required to make the page, sends the page to the asking for customer and annihilates the page assets from the server. Between two page demands, Web server and the customers are separated with one another, and estimations of page variables and controls are not saved over the page demands.),

the server processes any code you attached to the button click event, creates a new page with the latest state of the page, and sends it back to the browser). That's one round trip.

When you can use Server.Transfer
  • When you do not want to round trip , because Server.Transfer direct communicate to the server or say "Server.Transfer" it directly communicate with the server to change the page hence it saves a roundtrip in the whole process and in case of "Responce.Redirect"  it first sends the request for the new page to the browser then browser sends the request for the new page to the webserver then after your page changes.
  • When you want to transfer page on same server . Suppose you write the code Server.Transfer("www.google.com");  It will raise error , in this case you can use "Responce.Redirect".
  • When you do not want to update the clients url history list or current url.

Monday, January 18, 2016

Generic in C# with example?



Generic can be defined as <T> sign after the class name, by using the generic there is no need of boxing and unboxing. Generic also can be implemented with interfaces, delegates and methods.

Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    class Class1<T>
    {
        T i;
        public T prop1
        {
            get
            {
                return i;
            }
            set
            {
                i = value;
            }
        }
    }
}


Code on button click:
Class1<int> obj = new Class1<int>();
        private void button1_Click(object sender, EventArgs e)
        {

            obj.prop1 = 100;
            int x = obj.prop1;
            MessageBox.Show(x.ToString());
        }

Output : 100

Friday, January 1, 2016

Write Dynamically Text on Image in ASP.NET C#

In this article, I am going to explain how to write some text on a image in ASP. net c#.

Follow given below step to write text on an image in asp.net c#

Step 1

Go to Menu File->New-Project


Step 2

After clicking on project a new window will be open

select ASP.NET Web Application and write the name "DynamicTextOnImage" and click on "OK" button.


Code that write text on image

string name = "Dear Reader,";
 
                Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath(@"happynewyear.jpg"));
                Graphics graphicImage = Graphics.FromImage(bitMapImage);
 
                Color colorStringColor = System.Drawing.ColorTranslator.FromHtml("#ffffff");
                graphicImage.DrawString(name, new Font("Arial", 15, FontStyle.Bold), new SolidBrush(colorStringColor), new Point(100, 8));
 
                string stringOutPutFileName = Server.MapPath("Image\\happynewyear.jpg");
 
                using (MemoryStream memory = new MemoryStream())
                {
                    using (FileStream fs = new FileStream(stringOutPutFileName, FileMode.Create, FileAccess.ReadWrite))
                    {
                        bitMapImage.Save(memory, ImageFormat.Jpeg);
                        byte[] bytes = memory.ToArray();
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
                graphicImage.Dispose();
                bitMapImage.Dispose();
                bitMapImage.Dispose();

aspx.cs code

using System;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
 
namespace DynamicTextOnImage
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
            try
            {
                string name = "Dear Reader,";
 
                Bitmap bitMapImage = new System.Drawing.Bitmap(Server.MapPath(@"happynewyear.jpg"));
                Graphics graphicImage = Graphics.FromImage(bitMapImage);
 
                Color colorStringColor = System.Drawing.ColorTranslator.FromHtml("#ffffff");
                graphicImage.DrawString(name, new Font("Arial", 15, FontStyle.Bold), new SolidBrush(colorStringColor), new Point(100, 8));
 
                string stringOutPutFileName = Server.MapPath("Image\\happynewyear.jpg");
 
                using (MemoryStream memory = new MemoryStream())
                {
                    using (FileStream fs = new FileStream(stringOutPutFileName, FileMode.Create, FileAccess.ReadWrite))
                    {
                        bitMapImage.Save(memory, ImageFormat.Jpeg);
                        byte[] bytes = memory.ToArray();
                        fs.Write(bytes, 0, bytes.Length);
                    }
                }
                graphicImage.Dispose();
                bitMapImage.Dispose();
                bitMapImage.Dispose();
            }
            catch (Exception ex)
            {
 
            }
        }
    }
}
 
Image before writing text on image
 
image source
 


After writing text on image