我把这段代码放在一起,想知道如何从 .config 或 .ini 文件中调用某些数据。我已经研究过 AppSettings 和 ConfigurationManager 但对于菜鸟大脑来说计算太多了:-)
我已将 system.configuration 引用类添加到引用类列表中。基本上,我希望 MySQL 的变量存储在外部文件中,最终用户可以稍后更改。我不能把整个代码,因为它说我已经超过 3000 行或什么的。
DBServer = RemoteServer
dataBase = myDatabase
user = root
password = [the password here]
我已经用app.config尝试了以下代码,但仍然没有
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="constring" connectionString="server=localhost; database=SchoolDB; user id=root; password=Pa55w0rd;"/>
</connectionStrings>
</configuration>
在Mainwindow.cs中替换了以下内容
string constring = "datasource=localhost;port=3306;username=root;password=Pa55w0rd";
有了这个
string constring = ConfigurationManager.ConnectionStrings["dbconnectionstring"].ConnectionString;
然后我得到这个错误
“你调用的对象是空的”
好的,这是Mainwindow.cs
public partial class Portal : Form
{
public Portal(string UserName)
{
InitializeComponent();
lbl_username.Text = UserName;
timer1.Start();
txt_staff_password1.PasswordChar = '*';
load_loan_laptops();
}
DataTable dbdataset;
void load_loan_laptops()
{
//string constring = "datasource=localhost;port=3306;username=root; password=Pa55w0rd";
string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
string Query = "Select * from schooldb.loans where Avail = 'yes';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string devices = myReader.GetString("Device_Name");
cmb_acer_loan.Items.Add(devices);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conDataBase.Close();
}
请有人帮助解决这个问题。