Display records in datagridview when combobox items are selected

Satyapriyanayak
Posted by Satyapriyanayak under C# category on | Points: 40 | Views : 4186
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Display_records_datagridview_combo
{
public partial class Form1 : Form
{
string ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["dsn"];
OleDbCommand com;
string str;
OleDbDataAdapter oledbda;
DataSet ds;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("Select");
comboBox1.Text = "Select";
comboBox1.Items.Add("1");
comboBox1.Items.Add("2");
comboBox1.Items.Add("3");
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(ConnectionString);
if (comboBox1.SelectedItem.ToString() == "1")
{
con.Open();
str = "select top 1 * FROM subject";
com = new OleDbCommand(str, con);
oledbda = new OleDbDataAdapter(com);
ds = new DataSet();
oledbda.Fill(ds, "subject");
dataGridView1.DataMember = "subject";
dataGridView1.DataSource = ds;
con.Close();
}
else if (comboBox1.SelectedItem.ToString() == "2")
{
con.Open();
str = "select top 2 * FROM subject";
com = new OleDbCommand(str, con);
oledbda = new OleDbDataAdapter(com);
ds = new DataSet();
oledbda.Fill(ds, "subject");
dataGridView1.DataMember = "subject";
dataGridView1.DataSource = ds;
con.Close();
}
else if (comboBox1.SelectedItem.ToString() == "3")
{
con.Open();
str = "select top 3 * FROM subject";
com = new OleDbCommand(str, con);
oledbda = new OleDbDataAdapter(com);
ds = new DataSet();
oledbda.Fill(ds, "subject");
dataGridView1.DataMember = "subject";
dataGridView1.DataSource = ds;
con.Close();
}
else
{
dataGridView1.DataSource = null;
}
}
}
}

Comments or Responses

Posted by: jnrprogrammer-22113 on: 5/8/2013 Level:Starter | Status: [Member] | Points: 10
Sometimes it is good to add some coments/screen shots on the code........it helps us as we are begginers



Login to post response