• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

how to add data in dropdown using database using C#.net

hello,

i know its a easy question but i would to know .. please write the code..

i want to know how could i select the one row from database and insert it into my dropdown.. using C#.net

suppose:
query str = "select customerName from Customer where id=" '+custId+' "=customerId";

i want to select those customers whoz id is same which i pass via parameter and check the database id.. kindly give the code..

thanks..
0
AVARICESOFT
Asked:
AVARICESOFT
  • 2
1 Solution
 
muhammadyasirCommented:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList();
        }
    }
 
    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    }
 
    private void BindDropDownList()
    {
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT Top(20)* FROM Customers";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
 
            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DropDownList1.DataSource =dt;
                DropDownList1.DataTextField = "ContactName"; // the items to be displayed in the list items
                DropDownList1.DataValueField = "CustomerID"; // the id of the items displayed
                DropDownList1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
    }
}

Open in new window

0
 
muhammadyasirCommented:
Change Select query to your querylike this:
select customerName from Customer where id=' "'+custId+" ' ";

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now