Wednesday, 1 August 2018


Combobox:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            this.textBox1.Text = comboBox1.SelectedItem.ToString();

            textBox2.Text = string.Empty;
            foreach (var item in comboBox1.Items)
                textBox2.Text += item.ToString();
        }
 
 
//to get the particular data
foreach(DataRowView item in cmbUser.Items)
{
    if(item.Row[0].ToString() == "something")\\gets value displayed
    {
        //do something
    }
}
 
//using for loop
 
for (int i = 0; i < myComboBox.Items.Count; i++)
{
     string value = myComboBox.GetItemText(myComboBox.Items[i]); 
}
 

Listbox:
if (ListBox1.Items.Count > 0)
        {
            for (int i = 0; i < ListBox1.Items.Count; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    string selectedItem = ListBox1.Items[i].Text;
                    //insert command
                }
            }
        }

Or
public string GetListBoxSelStringInComma(ListBox Listbox1)
{
string selectedItem = "";
if (Listbox1.Items.Count > 0)
{
for (int i = 0; i < Listbox1.Items.Count; i++)
{
if (Listbox1.Items[i].Selected)
{
if (selectedItem == "")
selectedItem = Listbox1.Items[i].Text;
else
selectedItem += "," + Listbox1.Items[i].Text;
}
}
}
return selectedItem;
}
Gridview:

SP:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }
 
}
DataTable GetData()
{
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["testconection"].ConnectionString))
    {
        con.Open();
        using (SqlCommand cmd = new SqlCommand("select id , name from tableName ",con))
        {
 
            SqlDataAdapter adpt = new SqlDataAdapter(cmd);
            adpt.Fill(dt);
        }
 
    }
    return dt;
}

Sql:
protected void Page_Load(object sender, EventArgs e){
    if(!IsPostBack)
        BindGridView();   
}
 
private void BindGridView() {             
    DataTable dt = new DataTable();           
    SqlConnection con = null;         
 
    try {
        string sQuery = "SELECT ID, Name, Salary FROM EmpDetail";
 
        SqlConnection con = new SqlConnection(sConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand(sQuery, con); 
        SqlDataReader sdr = cmd.ExecuteReader();
 
        dt.Load(sdr);
        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }
    catch{ }
    finally{
        dt.Dispose();
        con.Close();
    }
}