12 Feb 2014

dropdownlist (or) combobox data binding code in asp.net c#

In this post, I explained combobox binding in single line of code, we use one class file, for every combobox we call that class method. you can call same for all comboboxes in your application.

Aspx.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace company
{
    public partial class valid : Telerik.WinControls.UI.RadForm
    {
        public valid()
        {
            InitializeComponent();
        }
        CommonFunctions objCom = new CommonFunctions();
        SqlConnection con = new SqlConnection(Connections.con);

        private void Auction_Load(object sender, EventArgs e)
        {
            objCom.setComboBox("Select '0' CODE,'-- SELECT --' NAME UNION select CODE,NAME from MASTER", "NAME", "CODE", cmbName);
        }
}
}

CommonFunctions.cs class code


using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace SCG_CHITS
{
    public class CommonFunctions
    {
        Connections objCon = new Connections();
   public void setComboBox(string query, string dataText, string dataValue, System.Windows.Forms.ComboBox combo)
        {
            SqlConnection con = new SqlConnection(Connections.con);
            SqlDataAdapter sqlDa = new SqlDataAdapter(query, con);
            DataSet dsData = new DataSet();
            sqlDa.Fill(dsData, "Details");

            combo.DataSource = dsData.Tables[0];
            combo.DisplayMember = dataText;
            combo.ValueMember = dataValue;
            combo.SelectedIndex = 0;
        }
}

}

No comments:

Post a Comment