I'm a beginner of learning C#. I've written this code to display data from database in a combobox with a connection in the same form, and then my teacher asked me to create a class to for the connection and call it from any form I'm using.
And I've already made my connection here. Is it just to remove the code to a new class and just call? Because I found many lessons on the internet creating code for the connection which is different from mine.
This code is to display data in a combobox
SqlConnection con = new SqlConnection("Data Source");
SqlCommand cmd = new SqlCommand("Select ", con);
// con.Open();
SqlDataReader DR1;
try
{
con.Open();
DR1 = cmd.ExecuteReader();
while (DR1.Read())
{
int BayN = Convert.ToInt32(DR1["BayNumber"]);
comboBox1.Items.Add(BayN);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
and the other connection is to display the data 8 rows to textboxes :
SqlConnection con = new SqlConnection("Data Source");
DataSet dsa = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select ='" + comboBox1.Text.Trim() + "';", con);
da.Fill(dsa);
for (int i = 0; i <= 8; i++)
{
for (int k = 0; k <= 8; k++)
{
textBox1.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label2.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox2.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label4.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox3.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label6.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox4.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label8.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox5.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label10.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox6.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label12.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox7.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label14.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
textBox8.Text = dsa.Tables[0].Rows[i++]["PatientId"].ToString();
label16.Text = dsa.Tables[0].Rows[k++]["Status"].ToString();
}
}
I'm so sorry if I went too deep or in details, but to make it clear (:
and I'm lost now because I'm using DataSet and DataReader is possible to call them from another class?
SqlCommand cmd = new SqlCommand("Select ", con);where is the actualSelect Statementfor (int i = 0; i <= 8; i++) { for (int k = 0; k <= 8; k++) {unnecessary code you need to understand how to iterate over the DataTable that fills a DataTable or DataSet.. also it's easier to fill a DataTable than to return the DataSet unless you are returningDataSet.Tables[0]