Jevon Jevon - 17 days ago 6
C# Question

Reading tables from SQL Server Express database

I am trying to read my tables that are contained within my database in SQL Server Express, but it keeps coming up empty. What is it that am doing wrong?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";

string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";

using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();

command.ExecuteNonQuery();
}
}


Updated but still empty:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {

string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
SqlCommand cmd2 = new SqlCommand(query, con2);

SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{

comboBox1.Items.Add((string)dr2[0]);

}


}


catch (Exception ex)
{

MessageBox.Show(ex.ToString());
}}


Latest Updated code. Think I figured it but still showing empty:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try {

string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
SqlConnection con2 = new SqlConnection(connectionString);
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);

SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{

string Dtables = dr2.GetString(dr2.GetOrdinal("TABLE_NAME"));
comboBox1.Items.Add(Dtables);

}

}

catch (Exception ex)
{

MessageBox.Show(ex.ToString());
}}


Full class:

namespace unique_database{ public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{

}

private void button2_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query = "CREATE TABLE [dbo].[" + textBox1.Text + "](" + "[Code] [varchar] (13) NOT NULL," +
"[Description] [varchar] (50) NOT NULL," + "[NDC] [varchar] (50) NULL," +
"[Supplier Code] [varchar] (38) NULL," + "[UOM] [varchar] (8) NULL," + "[Size] [varchar] (8) NULL,)";


using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}

SqlConnection con = new SqlConnection("Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True");
string filepath = textBox2.Text; //"C:\\Users\\jdavis\\Desktop\\CRF_105402_New Port Maria Rx.csv";
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split(',');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}

while (!sr.EndOfStream)
{
value = sr.ReadLine().Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = textBox1.Text;
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
bc.Close();
con.Close();

}

private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";


if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.textBox2.Text = openFileDialog.FileName;
}
}

private void FillCombo()
{
try
{

string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
using (SqlConnection con2 = new SqlConnection(connectionString))
{
con2.Open();
string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES ";
SqlCommand cmd2 = new SqlCommand(query, con2);

SqlDataReader dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{
int col = dr2.GetOrdinal("TABLE_NAME");
comboBox1.Items.Add(dr2[col].ToString());
}

}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

Answer

Ok, first, don't use comboBox1_SelectedIndexChanged to fill comboBox1. use YourForm.OnLoad event, the form constructor, or click a button, but don't use SelectedIndexChanged to fill itself, because you're executing this procedure every time you select one item of comboBox1.

To get column index simply use: dr2.GetOrdinal("TABLE_NAME");

private void FillCombo()
{
    try 
    {
        string connectionString = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
        using (SqlConnection con2 = new SqlConnection(connectionString))
        {
            con2.Open();
            string query = "SELECT * FROM INFORMATION_SCHEMA.TABLES";
            SqlCommand cmd2 = new SqlCommand(query, con2);

            SqlDataReader dr2 = cmd2.ExecuteReader();
            while (dr2.Read())
            {
                int col = dr2.GetOrdinal("TABLE_NAME");
                comboBox1.Items.Add(dr2[col].ToString());
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
Comments