帮助新接触C#变量的人 [英] Help someone new to C# variables
本文介绍了帮助新接触C#变量的人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过按按钮将数据保存到数据库中,但是由于变量的定义位置,这些变量似乎是私有的.我试图移动它们的定义位置,但这似乎还会产生其他错误.
I am trying to save data to a database on a button push, but the variables seem to be private by the nature of where they are defined. I have tried to move where they are defined, but this seems to produce other errors.
给出一个修复程序,为什么要这样修复?
Given a fix, why was it fixed that way?
代码如下.
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.
}
}
}
推荐答案
您在构造函数中声明了 dTable
和 adapter
,因此它很快就超出了范围构造函数完成后.
You're declaring dTable
and adapter
in the constructor, so it goes out of scope as soon as the constructor is completed.
您要将变量声明移到主类中,例如:
You want to move the variable declarations out into the main class, like:
public partial class Form1 : Form
{
private DataTable dTable;
private OleDbDataAdapter adapter;
Public Form1()
{
... your setup here ...
dTable = new DataTable();
... etc ...
}
}
这篇关于帮助新接触C#变量的人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文