2

我正在 vb.net 2010 中设计一个 Windows 窗体。这是一个带有两个控件的简单窗体。一个是 datagridview 以表格形式显示数据,另一个是图表控件,它从 gridview 获取数据以绘制图表。我还有一个组合框,可以帮助选择我想要为其创建表格或图表的变量。此外,还有两个按钮,一个标记为“表格”,单击它会使用来自外部 excel 文件的数据填充网格视图。另一个标记为“绘图”的按钮绘制了导入到 gridview 中的数据。

假设我在组合框中有三个变量,“实际 GDP”、消费、投资。在运行时,我第一次选择任何变量时,它工作正常。但是在同一次运行期间,如果我选择另一个变量,那么 gridview 可以导入变量但 plot 无法绘制图表。绘图找不到变量,因为它仍在寻找第一个变量,而在 gridview 我有第二个变量的表。如果我们在显示第一个变量后选择另一个变量,则网格视图和绘图之间似乎存在脱节。

如果我关闭运行并重建并选择另一个变量,它工作正常。但是在该运行期间,如果我选择另一个变量,它会失败。这是我的代码:

Public Class Form1
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter

Dim myStr1, myStr2, myStr3 As String
Dim msgStr, msgEnd, defValStr, defValEnd, _
   title, myValStr, myValEnd As String

Public Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    myStr1 = selectVariable.SelectedItem
    MsgBox("You have chosen " & myStr1)
    ' Defining a InputBox to enter Sample Period
    ' Start Period
    msgStr = "Enter your Starting time period: Between 1980 and 2012"
    defValStr = "1982"
    title = "Define Sample Time Period"
    myValStr = InputBox(msgStr, title, defValStr)
    ' End Period
    msgEnd = "Enter your Ending time period: Between 1980 and 2012"
    defValEnd = "2012"
    title = "Define Sample Time Period"
    myValEnd = InputBox(msgEnd, title, defValEnd)
    Select Case myStr1
        Case "Real GDP"
            myStr2 = "xgdp"
        Case "Consumption"
            myStr2 = "CP"
        Case "Investment"
            myStr2 = "IP"
    End Select

    myStr3 = String.Concat("select", " ", "FY", ",", myStr2, " ", "from", " ", "[Dataset$]", " ", "where", " ", "FY>=", myValStr, " ", "and", " ", "FY<=", myValEnd)
    MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='J:\Rushad\MOF\EViews Stuff\Data_Macro_Model.xls';Extended Properties=Excel 8.0;")
    MyCommand = New System.Data.OleDb.OleDbDataAdapter(myStr3, MyConnection)
    MyCommand.TableMappings.Add("Table", "Net-informations.com")
    DtSet = New System.Data.DataSet
    MyCommand.Fill(DtSet)
    DataGridView1.DataSource = DtSet.Tables(0)
    MyConnection.Close()
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    Chart1.DataSource = DtSet
    Chart1.Series.Add(myStr2)
    Chart1.Series(myStr2).XValueMember = "FY"
    Chart1.Series(myStr2).YValueMembers = myStr2
End Sub

End Class
4

1 回答 1

0

您应该尝试将数据源绑定到 BindingSource 并将 Binding 源绑定到数据网格

BindingSourceExample.DataSource = DataToBind
DataGridView.DataSource = BindingSourceExample

至少我会这样做!

于 2013-10-17T23:10:10.480 回答