简体   繁体   English

通过文本框循环C#

[英]loop through textboxes c#

I have 5 text-boxes and I want to loop over them and get each text-box value and insert it into a table on a separate row. 我有5个文本框,我想遍历它们并获取每个文本框值,并将其插入到单独行中的表中。 How can I do that? 我怎样才能做到这一点? I tried something like this: 我尝试过这样的事情:

TextBox[] rasp = new TextBox[] { textbox1, textBox2, textBox3, 
                                 textBox4, textBox5 };

foreach (TextBox  raspuns in rasp) {
     SqlConnection con = new SqlConnection(
  ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
     SqlCommand cmd = new SqlCommand(
        "INSERT INTO Raspunsuri Values('" + raspuns +"',@cnp,@data,'5')", con);
     cmd.Parameters.AddWithValue("@cnp", Session["sesiune_cnp"]);
     //cmd.Parameters.AddWithValue("@raspuns", raspuns);
     cmd.Parameters.AddWithValue("@data", DateTime.Now.ToLocalTime());
}

You probably meant: 您可能的意思是:

 SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + raspuns.Text +"',@cnp,@data,'5')", con);

instead of: 代替:

 SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values('" + raspuns +"',@cnp,@data,'5')", con);

As you cannot concatenate string and TextBox as it is an object whose one of fields is Text which contains the text entered into it. 由于您无法将stringTextBox连接在一起,因为它是一个对象,其字段之一是Text ,其中包含输入到其中的文本。

Note: Beware of SQL injection attacks, don't do this this way, instead resort back to your commented out solution with cmd.Parameters.AddWithValue("@raspuns", raspuns.Text); 注意:谨防SQL注入攻击,请不要这样做,而应使用cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);返回已注释掉的解决方案cmd.Parameters.AddWithValue("@raspuns", raspuns.Text); . Again, make sure to put raspuns.Text . 再次确保输入raspuns.Text

Assuming the problem is an error with this line: 假设问题是此行的错误:

//cmd.Parameters.AddWithValue("@raspuns", raspuns);

Change it to: 更改为:

cmd.Parameters.AddWithValue("@raspuns", raspuns.Text);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM