You're right with your assumption, it's possible to do this in a better way, without repeating almost the same code for each combobox. You have to identify which parts they have in common and which parts are different. Then you replace the differing parts by variables that you then provide with method-parameters instead. I've done this for you here; also I've improved some other aspects:
- the SqlConnection in a local using-block, not as a class-member
- removed the repeated opening and closing of the connection
- the SqlCommand and SqlDataReader in a using-block
- removed unneccessary casting of the row-cell
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=datatest;Integrated Security=True"))
{
conn.Open();
FillComboBox(conn, "tblcustomres", "personnam", comboBox1);
FillComboBox(conn, "tblitems", "items", comboBox2);
FillComboBox(conn, "tblloc", "location", comboBox3);
}
}
public void FillComboBox(SqlConnection conn, string table, string column, ComboBox comboBox)
{
string query = String.Format("SELECT {0} FROM {1};", column, table);
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
string item = dr[column].ToString();
comboBox.Items.Add(item);
}
}
}
}
I would also recommend you to rename your comboboxes something like "cbPerson", "cbItems", "cbLocation" and likewise, to give any other controls and variables meaningful names which will make it much easier to understand your code, even for yourself, especially when getting back to it after some weeks.