0

我在 c# windows 应用程序中以编程方式创建新列。

for (int i = 0; i < 10; i++)
{
    dataGridView1.Columns.Add(string.Format("colmun{0}", i), string.Format("number {0}", i));
}

如何将这些列保存在数据库中?

4

1 回答 1

0

这可能是很长的路要走,但是...

string myColumnName = string.Empty;
string myDataType = string.Empty;

SqlConnection myConnection = new SqlConnection("put your database connection string here");
myConnection.Open(); //you might have to put this inside the foreach loop

foreach(DataGridViewColumn myColumn in dataGridView1.Columns)
{
    myColumnName = myColumn.Name;
    myDataType = myColumn.ValueType.ToString();

if(myDataType.Contains("int"))
{
    myDataType = "int NULL";
}

if(myDataType.Contains("string"))
{
    myDataType = "varchar(255) NULL";
}

SqlCommand myCommand = new SqlCommand("alter table [put your table name here] add [" + myColumnName + "] " + myDataType);
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
}

myConnection.Close();
于 2012-11-19T00:28:05.217 回答