我有一个通过VS 2010(本地数据库文件选项)创建的SQL Server Compact数据库。
在表单加载(CategoryForm
)上,我将数据库中的值加载到DataGridView1
。我还以编程方式添加了ButtonColumn
,用于Delete
部分。
问题是:
Msgbox
上的印刷文字是按钮文字! (删除)(包含截图)p.s如下所述,当我注释掉额外的东西时,我会得到正确的值。我尝试了什么:
RowIndex
的部分和该索引处特定单元格的值。我在MsgBox
打印它们。我得到的值是正确的。例如,对于带有文字0
的第一行,test
索引和值test
。以下是我的进展以及截图:
CellContentClick
方法:
Private Sub DataGridView1_CellContectClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim i As String
'If e.ColumnIndex = 1 Then
'If e.RowIndex >= 0 And e.RowIndex <= DataGridView1.Rows.Count - 1 Then
i = DataGridView1.Rows(e.RowIndex).Cells(0).Value.ToString
MsgBox(e.RowIndex)
MsgBox(i)
SQLStringDelete = "DELETE FROM Category WHERE categoryname = '" & i & "'"
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
SQLCmd.Connection = SQLConn 'Sets the Connection to use with the SQL Command
SQLCmd.CommandText = SQLStringDelete 'Sets the SQL String
SQLCmd.ExecuteNonQuery() 'Executes SQL Command
'Create Adapter
Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
'Create DataSet
Dim Dataset As New DataSet
'fill the datset
DataAdapter.Fill(Dataset)
'attach dataset to the datagrid
With DataGridView1
.DataSource = Dataset.Tables(0)
.Columns(0).HeaderText = ""
.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
DataAdapter = Nothing
Dataset = Nothing
SQLConn.Close() 'Close the connection
End Sub
Form_Load
方法:
Private Sub CategoryForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConn.ConnectionString = ConnString 'Set the Connection String
SQLConn.Open() 'Open the connection
'Create Adapter
Dim DataAdapter As SqlCeDataAdapter = New SqlCeDataAdapter("SELECT categoryname FROM Category", SQLConn)
'Create DataSet
Dim Dataset As New DataSet
'fill the datset
DataAdapter.Fill(Dataset)
'attach dataset to the datagrid
With DataGridView1
.DataSource = Dataset.Tables(0)
.Columns(0).HeaderText = ""
.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End With
DataAdapter = Nothing
Dataset = Nothing
SQLConn.Close()
With buttonColumn
.Name = "DeleteButtonColumn"
.HeaderText = ""
.Text = "Delete"
.UseColumnTextForButtonValue = True
.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
.Width = 50
End With
If DataGridView1.Columns.Count = 1 Then
DataGridView1.Columns.Add(buttonColumn)
End If
End Sub
截图:
答案 0 :(得分:0)
事实证明,自动生成的列会在每次第二次单击时重新排列列。只需在表单加载和事件中设置DataGridView1.AutoGenerateColumns = false
即可。