本文介绍了如何从C#中的应用程序配置获取连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的app.config文件:
My app.config file:
<configuration>
<connectionStrings>
<add name="MegaPixelBizConn"
connectionString="Data Source=PSHERATH-PC;Initial Catalog=MegaPixelBiz;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
然后我创建了DBConnection文件:
Then I created DBConnection file:
class DBConnection
{
#region Database connection method
public SqlConnection Connect()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString();
try
{
conn.Open();
}
catch
{
}
return conn;
}
#endregion
}
这是我的登录表格:
SqlCommand cmd;
DataSet ds = new DataSet();
DBConnection db = new DBConnection();
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (txtUserName.Text == "" || txtPassword.Text == "")
{
lblError.Visible = true;
lblError.Text = "*Enter UserName and Password";
//MessageBox.Show(" Enter UserName and Password .");
return;
}
else
{
string sql = "SELECT * FROM login_info WHERE userName = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'";
cmd = new SqlCommand(sql, db.Connect());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i == 1)
{
this.Hide();
Home hm = new Home();
hm.Show();
ds.Clear();
}
else
{
lblError.Text = "*Not Registered User or Invalid Name/Password";
//MessageBox.Show("Not Registered User or Invalid Name/Password");
txtPassword.Text = "";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
但是当我的项目运行时,会出现以下错误:你调用的对象是空的."请给我一个解决方案.我使用所有合适的参考书
But when my project run, this error come:"Object reference not set to an instance of an object."please give me a solution. I use all suitable references
推荐答案
尝试
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);
应该可以
这篇关于如何从C#中的应用程序配置获取连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!