Trap the table names from database to combobox and display the selected table data in Datagridview?

Posted by gurramsra1-10894 under C# on 1/31/2012 | Points: 10 | Views : 2554 | Status : [Member] | Replies : 1
Hai.
My requirement is..
When we run the application It automatically add all the table names in specified database, into combobox, in formload event.
When we select a table from combobox that table data should be displayed in Datagridview. I have written the following code but it will displays first table data only. When we select
second table it will raise the exception that is "Can not find table1".
Please help me. what is the problem in this?



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.SqlClient;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("user id=sa;password=hari;database=employee;server=.");
SqlDataAdapter da;
DataSet ds;
SqlDataReader dr;
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

cmd = new SqlCommand("select name from sysobjects where type='u'", con);
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read() == true)
{
cmbTable.Items.Add(dr[0]);
}



con.Close();

}



private void cmbTable_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string s = "select * from " + cmbTable.SelectedItem.ToString();
da = new SqlDataAdapter(s, con);
ds = new DataSet();
da.Fill(ds, "X");

DGVSample.DataSource = ds.Tables[cmbTable.SelectedIndex];
//DGVSample.DataMember = cmbTable.SelectedItem.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

Sra1


Responses

Posted by: Blessyjees on: 1/31/2012 [Member] Bronze | Points: 25

Up
0
Down
Hi,

Try this

private void cmbTable_SelectedIndexChanged(object sender, EventArgs e) 

{
try
{
string s = "select * from " + cmbTable.SelectedItem.ToString();
da = new SqlDataAdapter(s, con);
ds = new DataSet();
da.Fill(ds);

DGVSample.DataSource = ds.Tables[0];
//DGVSample.DataMember = cmbTable.SelectedItem.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

}
}

Blessy Baby
Digitalmesh Softech pvt Ltd
https://blessybaby.wordpress.com/

gurramsra1-10894, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response