将列添加到SQL表并填充到datagridview

时间:2018-06-13 11:43:05

标签: sql vb.net datagridview

我有一个带有数据绑定datagridview的Windows窗体应用程序。我想在运行时添加列(如果用户想要添加更多列)。所以点击按钮我想添加列。我已将以下代码添加到事件中,它在表列的列表下的服务器资源管理器视图中添加了列,但在数据源窗口(在表下的列列表中)和datagridview中都没有在表定义中显示。

 Imports System.Configuration
 Imports System.Data.SqlClient

 Public Class Form3
     Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
       'TODO: This line of code loads data into the 'Small_databaseDataSet.newtable' table. You can move, or remove it, as needed.
       Me.NewtableTableAdapter.Fill(Me.Small_databaseDataSet.newtable)

     End Sub

     Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        AddColumn()
     End Sub

     Private Sub AddColumn()
          Dim connString As String = "Data Source=(localDb)\ProjectsV13;Initial Catalog=small database;Integrated Security=True"
          Dim dt As New DataTable

          Using conn As New SqlConnection(connString)

              Dim str As String = "ALTER TABLE newtable ADD " & TextBoxX1.Text & " INT null;"
              Using comm As New SqlCommand(str, conn)
              conn.Open()
              comm.ExecuteNonQuery()
          End Using

        End Using

        Validate()
        DataGridViewX1.Columns.Clear()
        NewtableTableAdapter.Update(Small_databaseDataSet.newtable)
        NewtableTableAdapter.Fill(Small_databaseDataSet.newtable)
        DataGridViewX1.DataSource = NewtableBindingSource

  End Sub

结束班

2 个答案:

答案 0 :(得分:0)

更改此行代码:

' Add the keyword NULL and brackets around the column name
Dim comm As New SqlCommand("ALTER TABLE testTable ADD [col1] INT NULL", conn)

如果我想让新列自动显示,我会重新查询数据库,检索该表上的数据,并将datagridview数据源设置为结果集,如:

'I assume the datagridview name is DataGridView1
DataGridView1.Columns.Clear()
DataGridView1.DataSource = USTDatabaseDataSet
DataGridView1.DataMember = "testTable" 
DataGridView1.DataBind()

答案 1 :(得分:0)

DataReader用于检索数据。由于没有检索到数据,因此除了成功或失败的返回值之外,没有任何内容被加载到您的DataTable中。即使出现错误,Using语句也可确保您的对象被关闭并正确处理。

Private Sub AddColumn()
        Dim connString As String = ConfigurationManager.ConnectionStrings("USTDatabaseConnectionString").ConnectionString
        Dim dt As New DataTable
        Using conn As New SqlConnection(connString)
            Using comm As New SqlCommand("ALTER TABLE testTable ADD col1 INT;", conn)
                conn.Open()
                comm.ExecuteNonQuery()
            End Using
            Using com2 As New SqlCommand("Select * From testTable;", conn)
                Using reader As SqlDataReader = com2.ExecuteReader
                    dt.Load(reader)
                    conn.Close()
                End Using
            End Using
        End Using
        DataGridView1.DataSource = dt
    End Sub