Reputation: 2505
I have a sql statement but i am not sure how to implement it so i can use it to populated a combobox in a winforms app.
This is how i had it in a previous app:
<asp:SqlDataSource ID="Sections" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection%>"
SelectCommand="SELECT e.DisplayName, e.ID , e.GUID
FROM ATable e
INNER JOIN RootTable re
ON e.ID = re.TablesID
AND re.InitID = 1">
</asp:SqlDataSource>
How can i alter this to suite a winforms combobox
----UPDATE----
After implementing suggestion below: i am getting an error when i compile stating that the method must be non-generic static class.
Code:
public partial class InfoGet : Form
{
public InfoGet()
{
InitializeComponent();
}
static string conString = "Data Source=.;Initial Catalog=MyConnection;Integrated Security=True";
public static void FillDropDownList(this ComboBox sections_drp, string conString)
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using(SqlDataAdapter sda = new SqlDataAdapter("SELECT....", conString))
{
DataTable dt = new DataTable();
sda.Fill(dt);
sections_drp.ValueMember = "ID";
sections_drp.DisplayMember = "DisplayName";
sections_drp.DataSource = dt;
}
}
}
}
Upvotes: 3
Views: 2051
Reputation: 67898
In a Windows Forms application you're going to need to go get it in code, or at least that's what I'm going to recommend. One possible approach is:
using (SqlConnection cnn = new SqlConnection(connString))
{
cnn.Open();
using (SqlDataAdapter sda = new SqlDataAdapater("SELECT e.DisplayName, e.ID , e.GUID FROM ATable e INNER JOIN RootTable re ON e.ID = re.TablesID AND re.InitID = 1", cnn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
comboBox.ValueMember = "ID";
comboBox.DisplayMember = "DisplayName";
comboBox.DataSource = dt;
}
}
Now, to make this code reusable, you might build an extension method like this:
namespace System.Windows.Forms
{
public static class ComboBoxExtensions
{
public static void Load(this ComboBox comboBox, string sql, string valueMember, string displayMember)
{
using (SqlConnection cnn = new SqlConnection(connString))
{
cnn.Open();
using (SqlDataAdapter sda = new SqlDataAdapater(sql, cnn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
comboBox.ValueMember = valueMember;
comboBox.DisplayMember = displayMember;
comboBox.DataSource = dt;
}
}
}
}
}
With that extension method it would be pretty easy to use:
comboBox.Load("SELECT e.DisplayName, e.ID , e.GUID FROM ATable e INNER JOIN RootTable re ON e.ID = re.TablesID AND re.InitID = 1",
"ID",
"DisplayName");
Upvotes: 1