Search This Blog

Wednesday, March 6, 2013

Fill Country code in Asp.net


if you have to fill country from the Country table of sql server database to dropdown list then you have to

Create function of fillcountry() in aspx.cs file

System.configuration is used to take connection string from the web.config file of your website.

code written in web.config is here :


<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
<appSettings>
<add key="cnnstr" value="Data Source=THEORY1\SQLEXPRESS;Initial Catalog=userdb;Integrated Security=True"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>



and in aspx.cs file write below code :


using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public partial class AddState : System.Web.UI.Page
{
    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["cnnstr"]);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            fillCountry();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into tbl_state values(@statename,@countryid)", cnn);
        cmd.Parameters.AddWithValue("@statename", txtstate.Text);
        cmd.Parameters.AddWithValue("@countryid", ddlcountry.SelectedValue);

        cnn.Open();
        cmd.ExecuteNonQuery();
        cnn.Close();
        txtstate.Text = "";
        txtstate.Focus();

        Response.Write("Record Inserted");
    }
    public void fillCountry()
    {
        SqlCommand cmd = new SqlCommand("select * from tbl_country", cnn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

        ddlcountry.DataSource = ds;
        ddlcountry.DataTextField = "countryname";
        ddlcountry.DataValueField = "countryid";
        ddlcountry.DataBind();
    }
}


Explanation of code :-

Execute the function fillCountry() from the page_load event of asp.net c# .

after that the dropdown list is filled so we have to fill it when the first time load of the page so we have to use
 if(!isPostBack) condition checking and inside that execute the fillCountry();

And now we have to insert the record in the datatable of state using button click event of the submit.

That's it.

Thank you.

For Learn C#.Net, ASP.Net, VB.Net Visit OurWebsite

1 comment:

  1. If You are interested for learning Asp.net + SQL Server Latest Version then Visit : www.vataliyatuitionclasses.com

    ReplyDelete