无法弄清楚为什么在使用字符串构建器的SQL语句之后datagridview没有使用新信息进行更新 [英] Can not figure out why datagridview isn't updating with new information after a SQL statement using a string builder

查看:72
本文介绍了无法弄清楚为什么在使用字符串构建器的SQL语句之后datagridview没有使用新信息进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:



here is my code:

Dim sqlconn As New SqlConnection("sqlconnectionstring")
            Dim da As New SqlDataAdapter(String.Empty, sqlconn)

            Dim sql As New StringBuilder("insert into [")
            sql.Append(Form1.TreeView1.SelectedNode.Text.Replace("]", "\]"))
            sql.Append("] ([Id], ")

            Dim sbOn As New StringBuilder(") values(@Id, ")
            Dim andRequired As Boolean = False

            If Not String.IsNullOrEmpty(IDTextBox.Text) Then
                da.SelectCommand.Parameters.AddWithValue("@Id", 
            Form1.DataGridView1.Rows.Count + 1)
            End If

            If Not String.IsNullOrEmpty(First_NameTextBox.Text) Then
                If andRequired Then
                    sql.Append(", ")
                    sbOn.Append(", ")
                End If

                sql.Append("[First_name]")
                sbOn.Append("@Firstname")

                da.SelectCommand.Parameters.AddWithValue("@Firstname", First_NameTextBox.Text)
                andRequired = True
            End If
sql.AppendFormat(sbOn.ToString + ")")
            da.SelectCommand.CommandText = sql.ToString()
            Dim dt As New DataTable
            da.Fill(dt)
            DataGridView1.DataSource = dt





当使用这个sql字符串时出来正确,但是datagridview表明它连接了变灰并显示没有数据,但如果我重新启动程序,它将显示新数据。



我尝试过:



尝试将da.select命令更改为da.insert命令。还尝试改变使用新的sql命令以对应Dataadaptor的事情,但这也不起作用。



when this is used the sql string comes out right, but the datagridview that its connected to turns gray and shows no data, but if I restart the program it will show the new data.

What I have tried:

tried to change the da.selectcommand to a da.insertcommand. Also tried to change things around a use a new sql command to correspond to the Dataadaptor, but that didn't work either.

推荐答案

我也碰到了这个问题,您可以通过首先将 DataGridView1.DataSource 设置为 Nothing 来解决此问题。

如果确实如此不够,添加 DataGridView.Rows.Clear()
I ran into this issue too, you can solve it by setting DataGridView1.DataSource to Nothing first.
If that does not suffice, add DataGridView.Rows.Clear()


这篇关于无法弄清楚为什么在使用字符串构建器的SQL语句之后datagridview没有使用新信息进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆