Wednesday, 4 April 2012

Using AdRotator in Asp.Net

To use AdRotator in Asp.Net you need to follow the following steps:

1. Create an aspx page, AdRotator.aspx

2. Add an AdRotator control to your page
Here AdvertisementFile contains url of the XML file, which is used to store the ad information.

3. Add an XML file to your project, adrotator.xml, the XML file must begin and end with an <Advertisements> tag. Inside the  <Advertisements> tag there may be several <Ad> tags which defines each ad.

adrotator.xml:

  
    Images/ad1.jpg
    http://www.google.com
    Alternate Text 1
    Keyword 1
    10
  
  
    Images/ad2.jpg
    http://www.google.com
    Alternate Text 2
    Keyword 2
    20
  
  
    Images/ad4.jpg
    http://www.google.com
    Alternate Text 3
    Keyword 3
    40
  


Here,
<ImageUrl>          The path to the image file
<NavigateUrl>      The URL to link to if the user clicks the ad
<AlternateText>    An alternate text for the image
<Keyword>          A category for the ad
 <Impressions>    The display rates in percent of the hits

Using Asp.Net User Control

To use Asp.Net User Control, you should follow the following steps:

1. Create a user control in your project, user control has .ascx extension and give it a name, here I have a user control named AddressUC.ascx

2. Add controls that you want the user control to display, For eg:


3. Add code for the tasks that the user control will perform, and create properties in the control if you want to be able to share information between the user control and the hosting page. For eg:

public partial class AddressUC : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
            
    }

    public class AddressEventAgrs : EventArgs
    {
        public AddressEventAgrs(string addressLine1, string addressLine2, string city, string state, string zip)
        {
            this.AddressLine1 = addressLine1;
            this.AddressLine2 = addressLine2;
            this.City = city;
            this.State = state;
            this.Zip = zip;
        }
        public string AddressLine1 { get; private set; }
        public string AddressLine2 { get; private set; }
        public string City { get; private set; }
        public string State { get; private set; }
        public string Zip { get; private set; }
    }

    public delegate void SaveButtonClickHandler(object sender, AddressEventAgrs e);
    public event SaveButtonClickHandler SaveButtonClick;

    //function to display a message to user
    private void MessageBox(string msg)
    {
        Label lbl = new Label();
        lbl.Font.Bold = true;
        lbl.Text = "";
        Page.Controls.Add(lbl);
    }

    //code for SAVE button click
    protected void ButtonSave_Click(object sender, EventArgs e)
    {
        if (SaveButtonClick != null)
        {
            SaveButtonClick(this, new AddressEventAgrs(txtAddressLine1.Text, txtAddressLine2.Text, txtCity.Text, txtState.Text, txtZip.Text));
        }
        if (txtAddressLine1.Text == string.Empty & txtCity.Text == string.Empty & txtState.Text == string.Empty & txtZip.Text == string.Empty)
        {
            MessageBox("Please enter all the information !");
        }
        else
        {
            MessageBox("You entered following information \\n\\nAddress: " + txtAddressLine1.Text + " "+txtAddressLine2.Text + "\\nCity: " + txtCity.Text + "\\nState: " + txtState.Text + "\\nZip: " + txtZip.Text);
        }
    }
}

4. Create an aspx page on which you want to use the user control, I have an aspx page named UserControl.aspx

5. Create an @Register directive on UserControl.aspx page that includes:


6. Add following code to UserControl.aspx page

public partial class UserControl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Control form = Page.FindControl("Form1");
        AddressUC uc = (AddressUC)LoadControl("AddressUC.ascx");
        form.Controls.Add(uc); 
    }
}

7.When you will run your UserControl.aspx page you will get something like:



Passing data from one webpage to another in Asp.net using Cross-Page Posting

Cross-page posting is used when data is collected on one web page and processed on another web page. To do this following steps should be followed:

1. Create a aspx page to collect data from user and name it as GetData.aspx. This form should look something like this:


2. Set the post back url of the SUBMIT button to the second page (DisplayData.aspx)


3. Code the cs file of GetData

public partial class GetData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    //code for SUBMIT button
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //if user has selected a picture then save it into the Images folder
        if (FileUpload1.HasFile)
            FileUpload1.SaveAs(MapPath("~/Images/" + FileUpload1.FileName));
        String filename = FileUpload1.FileName;
    }

    //define public properties which return information collected on the data collection page
    //property to return the name of person
    public string PageData1
    {
        get { return txtName.Text; }
    }

    //property to return the gender of person
    public string PageData2
    {
        get
        {
            if (RadioButtonMale.Checked)
                return RadioButtonMale.Text;
            else
                return RadioButtonFemale.Text;
        }
    }

    //property to return the address of person
    public string PageData3
    {
        get { return txtAddress.Text; }
    }

    //property to return the phone of person
    public string PageData4
    {
        get { return txtPhone.Text; }
    }

    //property to return the email of person
    public string PageData5
    {
        get { return txtEmail.Text; }
    }

    //property to return the photo of person
    public string PageData6
    {
        get { return FileUpload1.FileName; }
    }
}

4. Create a aspx page to process GetData.aspx's data and display it, name this aspx page as DisplayData.aspx, this page should look something like this:


5. Set the PreviousPageType directive on the processing page to point to the data collection page.

6. Code the cs file of DisplayData

public partial class DisplayData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblShowName.Text = PreviousPage.PageData1;
        lblShowGender.Text = PreviousPage.PageData2;
        lblShowAddress.Text = PreviousPage.PageData3;
        lblShowPhone.Text = PreviousPage.PageData4;
        lblShowEmail.Text = PreviousPage.PageData5;
        Image1.ImageUrl = "~/Images/" + PreviousPage.PageData6;
    }
}

7. Now when you run this application you will get something like this:




Using Multiview control in asp.net

To use Multiview control in asp.net first create an aspx page which looks something like this:


I have used three view inside a multiview control, one for personal information of a person, second for address, and third to upload the picture and submit.

Code for cs file:
protected void Page_Load(object sender, EventArgs e)
{
    //set the active view on page load
    MultiView1.SetActiveView(View1);
}
protected void Button1Continue_Click(object sender, EventArgs e)
{
    //when user click continue on view 1 set view 2 as active view
    MultiView1.SetActiveView(View2);  
}
protected void Button1Back_Click(object sender, EventArgs e)
{
    //when user clicks back button on view 2 set view 1 as active view
    MultiView1.SetActiveView(View1);
}
protected void Button2Continue_Click(object sender, EventArgs e)
{
    //when user click continue on view 2 set view 2 as active view
    MultiView1.SetActiveView(View3);
}
protected void Button2Back_Click(object sender, EventArgs e)
{
    //when user clicks back button on view 3 set view 2 as active view
    MultiView1.SetActiveView(View2);
}
protected void Button3Continue_Click(object sender, EventArgs e)
{
    //on submit button click the image uploaded by the user is saved into the Images folder in the project
    if (FileUpload1.HasFile)
        FileUpload1.SaveAs(MapPath("~/Images/" + FileUpload1.FileName));
}

When you run this, on startup only the first view that is regarding personal information will be displayed and when you fill the information and click continue second view is displayed and so on....

Pass Data from one form to another

To pass data from one form to another first you need to create two forms, one in which user will enter the information and second to display that information. The two forms will look something like:


Code to pass data from one form to another

//code for form 1
//code for SHOW button

//check if user has entered complete information
//if user has not entered complete information display a message to enter complete information
if (txtName.Text == "" && txtEmail.Text == "" && txtPhone.Text == "" && txtUsername.Text == "" && txtPassword.Text == "")
{
    MessageBox.Show("Enter complete information");
}
            
//if user has entered complete information
else
{
    //assign the form 1 control values to form 2 variables
    Form2.name = txtName.Text;
    Form2.phone = txtPhone.Text;
    Form2.email = txtEmail.Text;
    Form2.username = txtUsername.Text;

    //create an object of second form
    Form2 form2 = new Form2();

    //show the form by passing values
    form2.ShowDialog();

//code for form 2
public partial class Form2 : Form
{
    //declare variables 
    public static string name, email, phone, username;

    public Form2()
    {
        InitializeComponent();

        //assign the previous page values to the current page controls
        lblName.Text = name;
        lblShowPhone.Text = phone;
        lblShowUsername.Text = username;
        lblShowEmail.Text = email;
    }
}

Binding DataGridView with data from database

This post will show how to bind Datagridview control in C#.NET, and also how to format columns of datagridview control, eg. hiding some specific columns of the datagridview or setting the width of a particular colums. To bind datagridview following steps should be done:

1. Create a form as shown below



2. Code to bind datagridview

//code for ADD button click
private void btnAdd_Click(object sender, EventArgs e)
{
    try
    {
        //create database connection
        string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        //sql statement to insert information in database
        string sql = "INSERT INTO Person (Name, Age, Email, Phone) VALUES (@Name, @Age, @Email, @Phone)";

        //code to insert into database
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Age", txtAge.Text);
        cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
        cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
        cmd.CommandType = CommandType.Text;
        int result = cmd.ExecuteNonQuery();

        //check if record has been added to the database
        if (result > 0)
            MessageBox.Show("Record Added!");
        else
            MessageBox.Show("Failed to add!");

        //bind datagridview with data from database
        string query = "SELECT * FROM Person";
        SqlDataAdapter da = new SqlDataAdapter(query, connection);
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        DataTable dt = new DataTable();
        da.Fill(dt);
        BindingSource bs = new BindingSource();
        bs.DataSource = dt;
        dataGridView1.DataSource = bs;

        //set width of particular datagridview column 
        dataGridView1.Columns[2].Width = 160;

        //hide a particular datagridview column
        dataGridView1.Columns[4].Visible = false;

        connection.close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Tuesday, 3 April 2012

Update data in SQL Server databse

In this post I am going to retrieve data from database and then update the information in the database. To do you need to follow the following steps:

1. Create a form as shown below



2. Code to update data

//Code for GET DATA button
private void btnGetData_Click(object sender, EventArgs e)
{
    //create database connection
    string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
    SqlConnection connection = new SqlConnection(connectionString);
    connection.Open();

    //sql query to retrive data from database
    string sql = "SELECT * FROM Employees WHERE Name = @Name";
    SqlCommand cmd = new SqlCommand(sql, connection);
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@Name";
    param.Value = comboBoxEmployee.SelectedValue;
    cmd.Parameters.Add(param);
    SqlDataReader dr = cmd.ExecuteReader();
    string name = " ";
    string birthdate = " ";
    string address = " ";
    string email = " ";
    string phone = " ";
    string jobtitle = " ";
    while (dr.Read())
    {
        name = dr.GetValue(1).ToString();
        birthdate = dr.GetValue(2).ToString();
        address = dr.GetValue(3).ToString();
        email = dr.GetValue(4).ToString();
        phone = dr.GetValue(5).ToString();
        jobtitle = dr.GetValue(6).ToString();
    }
    dr.Close();

    //displaying retrieved data
    txtName.Text = name;
    dateTimePicker1.Text = birthdate;
    txtAddress.Text = address;
    txtEmail.Text = email;
    txtPhone.Text = phone;
    comboBoxJobTitle.Text= jobtitle;

    connection.Close();
}

//code for UPDATE button
private void btnUpdate_Click(object sender, EventArgs e)
{
    //create database connection
    string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
    SqlConnection connection = new SqlConnection(connectionString);
    connection.Open();

    //sql query to  update data
    string sql = "UPDATE Employees SET Name='" + txtName.Text + "', BirthDate='" + dateTimePicker1.Text + "', Address='" + txtAddress.Text + "', Email='" + txtEmail.Text + "', Phone='" + txtPhone.Text + "', JobTitle='" +comboBoxJobTitle.Text +"' WHERE Name=@Name";
    SqlCommand cmd = new SqlCommand(sql, connection);
    SqlParameter param = new SqlParameter();
    param.ParameterName = "@Name";
    param.Value = comboBoxEmployee.Text;
    cmd.Parameters.Add(param);
    cmd.CommandType = CommandType.Text;
    int result = cmd.ExecuteNonQuery();

    //check if record has been updated in the database
    if (result > 0)
        MessageBox.Show("Record Updated!");
    else
        MessageBox.Show("Failed to update!");

    connection.Close();
}

Binding Combobox with data from Database

In this post I am going to show how to bind combo box with data saved in database. To do this first I am going to insert data in the database and then retrieve that data and bind it with the combo box. For this you should follow the following steps.

1. Create a form as shown below



2. Code to bind combo box with data from database


//code for ADD button click
//when button is clicked to functions are called
private void btnAdd_Click(object sender, EventArgs e)
{
    insertInfo();
    getInfo();
}

//inserting information in the database
public void insertInfo()
{
    try
    {
        //create database connection
        string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        //sql statement to insert information in database
        string sql = "INSERT INTO Country (CountryName) VALUES (@CountryName)";

        //code to insert into database
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.Parameters.AddWithValue("@CountryName", txtCountryName.Text);
        cmd.CommandType = CommandType.Text;
        int result = cmd.ExecuteNonQuery();

        //check if record has been added to the database
        if (result > 0)
            MessageBox.Show("Country Added!");
        else
            MessageBox.Show("Failed to add!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

//to get the information from database and bind it with combo box
public void getInfo()
{
    try
    {
        //create database connection
        string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        //sql statement to retrieve information 
        string sql = "SELECT CountryName FROM Country";

        //code to retrieve data
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            //binding the retrieved data with combobox
            comboBox1.Items.Add(dr["CountryName"].ToString());
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Sunday, 1 April 2012

Save & Retrive Images to/from sql server database

In the earlier post I showed how to insert and retrieve simple data from database, In this post what I am going to do is insert images and retrieve them from database. I am going to show this in two main parts:
1. How to save images in the database
2. How to retrieve images back from the database

To save and retrieve images first you should create a table with required fields (Eg. Image Id, Image Name, Image). Lets us now first see how to save images into the database.

Save Images into database

1. Create a form as shown below


2. Code to insert images into database

public partial class Form1 : Form
{
    OpenFileDialog open;
    public Form1()
    {
        InitializeComponent();
    }

    //code for UPLOAD button
    //opens a file dialog for user to choose image to upload
    private void btnUpload_Click(object sender, EventArgs e)
    {
        open = new OpenFileDialog();
        open.InitialDirectory = @"C:\";
        open.Filter = "[JPG,JPEG,GIF,BMP]|*.jpg; *.jpeg; *.gif; *.bmp";
        open.ShowDialog();
    }

    //code for SAVE button
    //convert image to byte array and save it in databse
    private void btnSave_Click(object sender, EventArgs e)
    {
        if (txtImageName.Text == "")
        {
           MessageBox.Show("Enter image Name");
        }
        else
        {
            FileStream fs = new FileStream(@open.FileName, FileMode.Open, FileAccess.Read);
            byte[] image = new byte[fs.Length];
            fs.Read(image, 0, Convert.ToInt32(fs.Length));
            string name = txtImageName.Text;

            //create database connection
            string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();

            //sql statement to insert image into database
            string sql = "INSERT INTO Images (ImageName, Image) VALUES (@ImageName, @Image)";

            //code to insert into database
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@ImageName", name);
            cmd.Parameters.AddWithValue("@Image", image);

            //check if image is added to database
            int result = cmd.ExecuteNonQuery();
            if (result > 0)
                MessageBox.Show("Image Successfully Added!");
            else
                MessageBox.Show("Failed to Add Image!");
        }
            
    }
}
 
Retrieve Images from database

1. Create a form as shown below 


 2. Code for View button 

//create database connection
string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//sql query to retrive data from database
string sql = "SELECT Image FROM Images WHERE ImageName = @ImageName";
SqlCommand cmd = new SqlCommand(sql, connection);
SqlParameter param = new SqlParameter();
param.ParameterName = "@ImageName";
param.Value = comboBox1.SelectedValue;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
    //display the retrieved image
    MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Image"]);
    pictureBox1.Image = Image.FromStream(ms);
    pictureBox1.Refresh();
}
 

Friday, 30 March 2012

Save & Retrive Data to/from sql server database

In this post I am going to show two main things:
1. How to save data in the database
2. How to retrieve data back from the database

I am doing this in a simple and very easy way. To save and retrieve data first you should create a table with required fields. Lets us now first see how to save data into the database.

Save data into database

1. Create a form as shown below


2. Code for ADD button

try
{
//create database connection
string connectionString = "Data Source=abc;
    Initial Catalog=abc;User ID=abc;Password=abc";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//sql statement to insert employee information in database
string sql = "INSERT INTO Employees 
    (Name, BirthDate, Address, Email, Phone, JobTitle) 
    VALUES (@Name, @BirthDate, @Address, @Email, @Phone, @JobTitle)";

//code to insert into database
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@BirthDate", dateTimePicker.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
cmd.Parameters.AddWithValue("@Phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@JobTitle", comboBox.SelectedItem);
cmd.CommandType = CommandType.Text;
int result = cmd.ExecuteNonQuery();

//check if record has been added to the database
if (result > 0)
    MessageBox.Show("Record Added!");
else
    MessageBox.Show("Failed to add!");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}


Retrieve data from database

1. Create a form as shown below


 2. Code for SEARCH button
 
//create database connection
string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//sql query to retrive data from database
string sql = "SELECT * FROM Employees WHERE Name = @Name";
SqlCommand cmd = new SqlCommand(sql, connection);
SqlParameter param = new SqlParameter();
param.ParameterName = "@Name";
param.Value = comboBox1.SelectedValue;
cmd.Parameters.Add(param);
SqlDataReader dr = cmd.ExecuteReader();
string name = " " ;
string birthdate = " ";
string address = " ";
string email = " ";
string phone = " ";
string jobtitle = " ";
while (dr.Read())
{
    name = dr.GetValue(1).ToString();
    birthdate = dr.GetValue(2).ToString();
    address = dr.GetValue(3).ToString();
    email = dr.GetValue(4).ToString();
    phone = dr.GetValue(5).ToString();
    jobtitle = dr.GetValue(6).ToString();
}
dr.Close();

//displaying retrieved data
lblDisplayName.Text = name;
lblDisplayBirthDate.Text = birthdate;
lblDisplayAddress.Text = address;
lblDisplayEmail.Text = email;
lblDisplayPhone.Text = phone;
lblDisplayJobTitle.Text = jobtitle;

 3. Following is the form with the data retrieved from database