帮助新的C#变量

Mat*_*att 2 c# variables

我试图在按钮按下时将数据保存到数据库,但变量似乎是私有的,因为它们的定义位置.我试图移动它们定义的位置,但这似乎产生了其他错误.

给定修复,为什么这样修复?

代码如下.

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.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ham 10

你在构造函数中声明dTable并且adapter一旦构造函数完成就会超出范围.

您希望将变量声明移动到主类中,例如:

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

    Public Form1()
    {
         ... your setup here ...
         dTable = new DataTable();
         ... etc ...
    }
}
Run Code Online (Sandbox Code Playgroud)