My concern is how to add comboBox1.DataSource and comboBox1.DisplayMember both codes in the class it self and how to pass combobox name as parameter from the form?
Form Code
SClass.Database db = new NSClass.Database();
db.comboFill(@"Select UserName from Staff");
comboBox1.DataSource = new BindingSource(db.tableNewGet, null);
comboBox1.DisplayMember = "UserName";
NS Class Code
private DataTable tableNew = new DataTable();
public DataTable tableNewGet
{
get { return tableNew; }
set { tableNew = value; }
}
public void comboFill(string query)
{
{
using (MySqlDataAdapter da = new MySqlDataAdapter(query, cs))
da.Fill(tableNew);
}
}
CodePudding user response:
In WinForms you have a number of options for ComboBox
, ultimately if you are not going to set DisplayMember
and ValueMember
yourself, but you want to allow dynamic queries, then you will need to write some code to resolve this.
You could create a helper method on the NS
class:
public void comboFill(ComboBox combo, string query, string displayMember)
{
this.comboFill(query);
combo.DataSource = new BindingSource(this.tableNewGet, null);
combo.DisplayMember = displayMember;
}
Then your code in the form should look like this:
SClass.Database db = new NSClass.Database();
db.comboFill(comboBox1, @"Select UserName from Staff", "UserName");
I will get blank columns if I run same code for multiple times for different query. How to avoid that?
Your code simply executes the query
sql and dumps it into a table structure that matches the output. The blanks come from your query, if you do not want blanks in the results, then adjust your query to omit these rows.
You will need to post the specific query and the output if you want specific advice, but in general it is not the code's fault that you wanted to query blank values.
Does this code prevent database injection issues?
Regarding Database Injection => This is only a real concern if the user interface provides a mechanism where the query string can be manipulated by the user. In this case you are safe from that, I am not going to say this is "the correct way to write it" but this specific code should be OK for now.
using TableAdapters is a recommended way to prevent injection attacks when using ADO.Net, but your implementation of MySqlDataAdapter
might still facilitate injection attacks if you do not pass through a parameterised query. If you only provide a generic string literal for both the ConnectionString
and the Query
then it is highly likely that elsewhere in your code you might be opening yourself to injection attacks.
You might consider ORMs like Entity Framework or nHibernate if you want to further protect yourself from Injection issues and to automate parameterisation of the actual SQL that is executed. (The ORM will generate the SQL for you from LINQ queries)