tags:

views:

191

answers:

4

text box set1 = 1 to 30 = in the query name = br1id to br30id

textbox set 2 = 1 to 30 = in the result output

i dont understand how to create a loop based on 30 diffrent textbox names?

i cant copy paste these lines 30 times editing the textbox names, that wold just look wrong.

try
{

   MySqlConnection mysqlCon = new MySqlConnection(
      "server= 195.159.253.229;" +
      "Database = bruker;" +
      "user id=bobby;" +
      "password=LoLOW###;");  

   MySqlCommand cmd1 = new MySqlCommand(
      "SELECT brukernavn From bruker where ID = '" + br1id.Text + "';", mysqlCon);

   mysqlCon.Open();

   navX[0] = cmd1.ExecuteScalar().ToString();
   br1txt3.Text = navX[0];   
}
+2  A: 

You will want to use a control enumerator.

Assuming that this is WinForms:

foreach(Control c in this.Controls) {
    if(c is TextBox)
        Console.WriteLine(c.Text);   
}

And actually, I think that will work for ASP.Net, too. (Even though Control is in a diferent namespace.)

HOWEVER!: This is what a datagrid was made for.

John Gietzen
yeah i was thinking about enums thats prolly the path i need to walk yeah.
Darkmage
+1  A: 

You really should reconsider your design if you have 600 TextBox controls. Holy cow.

Also, your SQL is very much subject to SQL injection.

What you're looking to to specifically can't be done, as there is no dynamic evaluation of C# at runtime. What you need to do is create a collection of the controls you want to use--in the order you want to use them--then enumerate over this list to use in your query. However, this query should absolutely be rewritten to use parameters.

Adam Robinson
A: 

Here's how to get a control by name inside a Form:

        // get control by name:
        TextBox tb = this.Controls["textBox1"] as TextBox;
        if (tb != null) {
            // your code here
        }
Paolo Tedesco
A: 

Yes to all previous answers, (600 textboxes? 600 for Ids and 600 more for the query results?) but if you really want to do this, as a technique, also change the SQL to:

StringBuilder sb = new StringBuilder(
         "SELECT brukernavn From bruker where ID In (");
foreach(Textbox tb in IdTextboxes)  sb.Append(tb.Text + ",");  
string SQL = sb.ToString(0,sb.Length - 1) + ")";

MySqlConnection mysqlCon = 
     new MySqlConnection("server=195.225.0.218; " +
          "Database = bruker; user id=huggy; password=LoLOW;");   
cmd1 = new MySqlCommand(SQL, mysqlCon);
Charles Bretana
thx will have a look at changing my Sql query in code :)
Darkmage