通过TextBox

时间:2016-03-11 10:56:01

标签: sql-server vb.net datagridview textbox

我有一个包含四个对象的简单表单:两个 TextBoxes ,一个 DataGridView 和一个 Button 。通过该按钮,我从这些对象中的SQL数据库加载一些数据。该表有两个字段,一个是文本字段(“MyOtherTextField”)和一个时间字段(“MyTimeField”)。我为绑定编写的代码如下:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Dim m_dt As DataTable

  Dim m_da As SqlClient.SqlDataAdapter
  Dim m_cn As SqlClient.SqlConnection
  Dim m_SelectCmd As SqlClient.SqlCommand
  Dim m_InsertCmd As SqlClient.SqlCommand
  Dim m_UpdateCmd As SqlClient.SqlCommand
  Dim m_DeleteCmd As SqlClient.SqlCommand
  Dim m_bmb As BindingManagerBase

  m_dt = New DataTable

  m_cn = New SqlClient.SqlConnection("My SQL Connection")

  m_SelectCmd = New SqlClient.SqlCommand("My Command String ", m_cn)

  m_SelectCmd.CommandTimeout = 500
  m_da = New SqlClient.SqlDataAdapter(m_SelectCmd)

  m_da.Fill(m_dt)

  If m_dt.Rows.Count = 0 Then

    TextBox3.DataBindings.Clear()
    TextBox1.DataBindings.Clear()

    TextBox3.DataBindings.Add("text", m_dt, "MyTimeField")
    TextBox1.DataBindings.Add("text", m_dt, "MyOtherTextField")

    TextBox3.Text = " "
    TextBox1.Text = " "

  Else
    TextBox3.DataBindings.Clear()
    TextBox1.DataBindings.Clear()

    TextBox3.DataBindings.Add("text", m_dt, "MyTimeField")
    TextBox1.DataBindings.Add("text", m_dt, "MyOtherTextField")
  End If

  m_bmb = BindingContext(m_dt)

  Dim CmdBuilder As SqlClient.SqlCommandBuilder = New SqlClient.SqlCommandBuilder(m_da)

  m_InsertCmd = CmdBuilder.GetInsertCommand
  m_UpdateCmd = CmdBuilder.GetUpdateCommand
  m_DeleteCmd = CmdBuilder.GetDeleteCommand

  m_da.InsertCommand = m_InsertCmd
  m_da.UpdateCommand = m_UpdateCmd
  m_da.DeleteCommand = m_DeleteCmd

  ' DataGridView column setup
  MyDataGridView.DataSource = Nothing
  With MyDataGridView
    .AutoGenerateColumns = False

    .ColumnCount = 2

    .Columns(0).DataPropertyName = "MyOtherTextField"
    .Columns(0).HeaderText = "Other Text Field Header Text"
    .Columns(0).Width = 165

    .Columns(1).DataPropertyName = "MyTimeField"
    .Columns(1).HeaderText = "Time Field Header Text"
    .Columns(1).Width = 90
  End With

  MyDataGridView.DataSource = m_dt

  m_cn.Close()
End Sub

数据加载工作,编辑数据在DataGridView和TextBox1(与SQL表的文本字段关联的那个)中都有效,但不在链接到时间字段的TextBox中。因此,如果我通过TextBox1编辑字段MyOtherTextField,它会正确更新该记录,但MyBoxField通过TextBox3不会发生同样的事情。我做错了什么?

感谢。

1 个答案:

答案 0 :(得分:0)

您应该使用蒙面编辑的文本框作为时间字段,以便根据需要设置格式。