Добавить элемент списка в SQL Столбцы сервера в качестве имени столбца - PullRequest
0 голосов
/ 20 марта 2020
foreach (string LB in listBox1.Items)
{
    SqlCommand SCA = new SqlCommand("create table " + textBox3.Text + "("+ 
    listBox1.Items[].ToString()+")",SC1); 
    SCA.ExecuteNonQuery();
}

Как добавить все элементы, используя l oop, чтобы добавить элементы на listbox.items в SQL Серверные столбцы только для имен столбцов?

Пример:

use listbox items to create table like this, only columns name

1 Ответ

0 голосов
/ 20 марта 2020

Вы пытаетесь создать несколько таблиц с одинаковым именем в al oop. Я полагаю, ваш код должен выглядеть примерно так:

// StringBuilder is better way to creating a string in a loop,
// because it doesn't allocate new string on each concatenation
StringBuilder command = new StringBuilder("create table ");
command.Append(textBox3.Text).Append("(");

string separator = "";

// It is better to give more descriptive names to variables
foreach (string columnName in listBox1.Items)
{
    // You forgot to specify column type
    command.Append(separator)
           .Append(columnName)
           .Append(" varchar(1000)");

    separator = ",";
}

command.Append(")");

// SqlCommand and SqlConnection implement IDisposable, 
// so it is better to wrap their instantiation by 'using' statement 
// in order to free corresponding resources
using (SqlCommand sqlCommand = new SqlCommand(command.ToString(), SC1)) {
    sqlCommand.ExecuteNonQuery();
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...