gpt4 book ai didi

c# - 帮助刚接触 C# 变量的人

转载 作者:行者123 更新时间:2023-11-30 19:04:23 24 4
gpt4 key购买 nike

我正在尝试通过按下按钮将数据保存到数据库,但变量似乎是私有(private)的,因为它们被定义的地方的性质。我试图移动它们的定义位置,但这似乎会产生其他错误。

如果有修复,为什么要这样修复?

代码如下。

namespace enable
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection favouriteConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.123.5\\Share\\Matt\\BugTypes.mdb");
string strSQL = "SELECT CategoryName, Show " + "FROM [Categories] WHERE Show = 'Yes' " + "ORDER BY CategoryName";
OleDbDataAdapter adapter = new OleDbDataAdapter(strSQL, favouriteConnection);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(adapter);
DataTable dTable = new DataTable();
adapter.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dataGridView1.DataSource = bSource;
adapter.Update(dTable);
}
private void button1_Click(object sender, EventArgs e)
{
adapter.Update(dTable);//this is the button that needs to do the save, but can't see the variables.
}
}
}

最佳答案

您在构造函数中声明了 dTableadapter,因此一旦构造函数完成,它就会超出范围。

您想将变量声明移出到主类中,例如:

public partial class Form1 : Form
{
private DataTable dTable;
private OleDbDataAdapter adapter;

Public Form1()
{
... your setup here ...
dTable = new DataTable();
... etc ...
}
}

关于c# - 帮助刚接触 C# 变量的人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/154446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com