Reputation: 33
I'm pretty new to c# and I'm struggling with this,
I'm trying to make a program that can send "items" to the names I type in the textboxes all at once with SQL stored produce.
I want to while loop textboxes so it changes from textBox1 to textBox2 and so on when it loops. I want to do this cause I have 45 texBoxes and a loop should be good I guess.
this is what I've tried:
int x = 1;
while (x < 46)
{
cmd.CommandText = "EXECUTE usp_GiftItem @sendUser, @SendNickname, @receiver, @itemname, @text, @paymentType, @bOutput";
cmd.Parameters.Clear();
cmd.Parameters.Add("@SendUser", SqlDbType.VarChar).Value = "123";
cmd.Parameters.Add("@SendNickname", SqlDbType.VarChar, 50).Value = textBox89.Text;
cmd.Parameters.Add("@receiver", SqlDbType.VarChar, 50).Value = textbox(x).Text;
cmd.Parameters.Add("@itemname", SqlDbType.VarChar).Value = textBox80.Text;
cmd.Parameters.Add("@text", SqlDbType.VarChar, 1024).Value = textBox88.Text;
cmd.Parameters.Add("@paymentType", SqlDbType.VarChar).Value = "0";
cmd.Parameters.Add("@bOutput", SqlDbType.VarChar).Value = "1";
cn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Item sent", "Success");
cn.Close();
x++;
}
The problem is at @recivers value
I hope you there is a solution to this. Thank you, Much appreciated
Upvotes: 0
Views: 1905
Reputation: 21969
You can simplify things if you do some preparation first. To example, you can create an array of items, where index of item is a TextBox
number and item itself is an object what will be used to generate bold part: cmd.Parameters.Add( "@blablabla", type, num ).Value .
So:
public class MyData
{
public string Text;
public SqlDbType Type;
public int Number;
public MyData(string text, SqlDbType type, int number = 0)
{
Text = text;
Type = type;
Number = number;
}
}
MyData[] data = new MyData[45] { new MyData("@bOutput", SqlDbType.VarChar), new MyData(...), ... };
TextBox[] control = new TextBox[45] {textBox1, textBox2, ... };
for(int i = 0; i < 45; i++)
cmd.Parameters.Add(data[i].Text, data[i].Type, data[i].Number).Value = control[i].Text;
There are still things to improve, to example, instead of enumerating TextBox
'es you may want to find them on the form (form1.Controls
). Instead of generating data[] - it can be a part of TextBox.Tag
, where you parse it and then generate parameters. Processing of the Number
can be optional, etc..
But this should give you an idea.
Upvotes: 1
Reputation: 6608
TextBox[] textBoxes = new TextBox[] { textBox1, textBox2, ... };
while(x ...)
{
something[x] = textBoxes[x].Text;
}
Upvotes: 4