Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为动态创建的文本框插入查询_C#_Sql Server - Fatal编程技术网

C# 为动态创建的文本框插入查询

C# 为动态创建的文本框插入查询,c#,sql-server,C#,Sql Server,我已经动态生成了一个文本框,需要将其插入查询写入我的SQLServer2005数据库。 问题是,当我编写插入查询时,我不能包含文本框名称,因为文本框将在运行时生成 我尝试使用以下逻辑: 请注意,我希望生成动态文本框,然后生成动态SQL查询。 String str=//will contain a data fetched from all the textboxes generated dynamically and will be seprated using a ','(as in a

我已经动态生成了一个文本框,需要将其插入查询写入我的
SQLServer2005
数据库。 问题是,当我编写插入查询时,我不能包含文本框名称,因为文本框将在运行时生成

我尝试使用以下逻辑:

请注意,我希望生成动态文本框,然后生成动态SQL查询。

   String str=//will contain a data fetched from all the textboxes generated dynamically and will be seprated using a ','(as in an insert statement).
此字符串
str
将直接传递到insert查询,以便直接获取所有值

但这种逻辑不起作用

请提供帮助。

几点

  • 你的方法让你容易受到攻击。这是一件坏事。您应该使用sqlCommand对象来执行SQL,使用参数对象来传递要插入的值,这将防止SQL注入攻击
  • 在插入到的表中的每列后面命名文本框

  • 希望这有帮助

    您需要在文本框生成时跟踪它们

    List<TextBox> TextBoxes = new List<TextBox>();
    
    如果你有你的专栏的名字

    string Columns = "@col0, @col1, @col2"; //etc
    
    string Query = @"INSERT INTO [Table]
                     (" + Columns.Replace("@", "") + ")
                     VALUES (" + Columns+ ")";
    
    使用参数化命令

    SqlCommand Command = new SqlCommand(Query, Connection);
    
    for (int i=0; i<TextBoxes.Count; i++)
    {
        Command.Parameters.AddWithValue("@col" + i, TextBoxes[i].Text);
    }
    
    Connection.Open()
    Command.ExecuteNonQuery();
    Connection.Close()
    
    SqlCommand=newsqlcommand(查询、连接);
    
    对于(int i=0;我需要解决这个问题……尝试了几种方法,但都不起作用。请帮助..最大文本框的数量是固定的吗?如果不是,您将如何确定表中的列数?@RaviSingh:不,先生。该数量将在运行时确定。我可以使用组合框获得表中的列数,并生成文本框的ame编号dynamically@user:然后创建一个包含以下字段的新表:
    ID int,textboxName(如果需要)varchar(),value varchar()
    。此
    Id
    字段将引用当前表中的Id。这将解决问题。@RaviSingh:不,先生,这不会解决我的问题。因为我希望在现有表中生成一个insert查询,该查询还将包括动态输入的新生成列,为这些列创建新的文本框。先生……是的,SQL注入可能会这可能是个问题。但首先,我无法在动态插入查询中导航。请不要叫我先生,我是以工作为生的。您知道要插入的表的名称吗?您知道表中列的名称吗?那么为什么您不能在列之后命名文本框?
    SqlCommand Command = new SqlCommand(Query, Connection);
    
    for (int i=0; i<TextBoxes.Count; i++)
    {
        Command.Parameters.AddWithValue("@col" + i, TextBoxes[i].Text);
    }
    
    Connection.Open()
    Command.ExecuteNonQuery();
    Connection.Close()