我在标题中收到了这个错误。
对于我的
cmd.Connection = Conn;
我有这个
public string Conn = connection.getConnection();
我正在使用Windows应用程序,我该如何解决这个问题?
这是我的完整代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Room : Form
{
public SqlDataReader re;
public string Conn = connection.getConnection();
public Room()
{
InitializeComponent();
}
private void Room_Load(object sender, EventArgs e)
{
..
..
..
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text.Length != 0 && textBox2.Text.Length != 0)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "insertToRoom";
cmd.Parameters.AddWithValue("@room_name", textBox1);
cmd.Parameters.AddWithValue("@room_rate", textBox2);
cmd.ExecuteNonQuery();
}
else
{
MessageBox.Show("Please fill in all the textbox.", "Wrong Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
答案 0 :(得分:1)
试试这种方式。首先从web.conf或app.conf获取连接字符串,然后创建一个sqlconnection以分配给sqlcommand。
var connectionString =
ConfigurationManager.ConnectionStrings["NameofConstringFromWebconfig"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection =new SqlConnection(connectionString);