在数据库中保存datagridview新列

时间:2012-11-18 20:30:32

标签: c# sql-server datagridview

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

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

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

1 个答案:

答案 0 :(得分: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();