# Two Datasets Same Query

I have a form that allows the user to select a server. This will execute the exact same query just on a different server.

private void QueryButton_Click(object sender, EventArgs e)
{
switch (this.FindByComboBox.SelectedIndex)
{
case 0:
ByTargetVDN();
break;
// ...
}
}
void ByTargetVDN()
{
int value = 0;
if (this.ValueTextBox.Text.Length > 0)
{
value = Convert.ToInt32(this.ValueTextBox.Text);
}
switch (this.ServerComboBox.SelectedIndex)
{
case 0:
var gr01 = new GR01.TargetVDNDataTable();
if (value == 0)
{
}
else
{
}
this.FindScriptsDataGrid.DataSource = gr01;
break;
case 1:
var ds01 = new DS01.TargetVDNDataTable();
if (value == 0)
{
}
else
{
}
this.FindScriptsDataGrid.DataSource = ds01;
break;
}
}


There has got to be a way I can streamline this. I was hoping for something along the lines of

switch (this.ServerComboBox.SelectedIndex)
{
case 0:
var ds = new GR01.TargetVDNDataTable();
break;
case 1:
ds = new GR01.TargetVDNDataTable();
break;
}
if (value == 0)
{
}
else
{
}
this.FindScriptsDataGrid.DataSource = ds;


but of course this doesn't work.

• If you're running the same query, just on a different server, why are you filling separate datasets (In your working code). – JohnP Jul 1 '14 at 22:14
• @JohnP Thank you, I was using the wizard to generate these datasets and your comment made me think WTF am I doing this with the wizard, wrote the datasets in hard code instead and now I am happy with the code. Check this post: codereview.stackexchange.com/questions/55893/… – aaronmallen Jul 2 '14 at 15:38

if (this.ValueTextBox.Text.Length > 0)
{
value = Convert.ToInt32(this.ValueTextBox.Text);
}


This will throw a nullpointerexception if Text is null, use TryParse instead

int value;
bool result = Int32.TryParse(ValueTextBox.Text, out value);
if(result){
// use value
}


I don't recommend you using SelectedIndex, because it breaks your code if the ordering get changed in the future, I would use SelectedItem instead.

Notice that you are repeating code, which is not a brilliant idea.

TheTypeForThis gr01 = null;
TheTypeForThis adapter = null;
switch (this.ServerComboBox.SelectedIndex)
{
case 0:
gr01 = new GR01.TargetVDNDataTable();
break;
case 1:
var ds01 = new DS01.TargetVDNDataTable();
break;
}

if (value == 0)
{
}
else
{

• I assume it's your style to refer to all class using "this.". That's not the usual way to do things but it is acceptable.
• Especially since you haven't included the definitions of classes GR01 and DS01 are, it's impossible to tell from this code snippet what gr01 and ds01 are.
• The biggest problem seems to be that you're declaring adapter and adapternew inside the switch. Move those declarations outside, and you should only need one variable.