放了个textbox,想运行程序后能在这个textbox里显示出统计次数的结果的,但是一无所获。sql代码在数据库里执行的时候是能成功统计出结果的。。求解原因
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("server=localhost;database=jtgl;user=sa;password=sa");
SqlCommand cmd = new SqlCommand("select count(bltype) from ajd where bltype=1", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ajd");
this.TextBox1.Text = ds.Tables[0].Rows[0][0].ToString();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("server=localhost;database=jtgl;user=sa;password=sa");
SqlCommand cmd = new SqlCommand("select count(bltype) from ajd where bltype=1", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ajd");
this.TextBox1.Text = ds.Tables[0].Rows[0][0].ToString();
}
那么LZ确定你的SqlConnection 连接串写对了吗?
SqlCommand cmd = new SqlCommand("select count(*) from ajd where bltype=1", cn);this.TextBox1.Text = cmd.ExecuteScalar().ToString()
1、cn.Open();
2、cmd.ExecuteScalar()
楼主去看下基础吧。。数据库没有打开如何执行呢。
返回第一行第一列使用:SqlCommand 的ExecuteScalar方法就行了。何必那么麻烦呢。
.
.
....那么应该是你赋值给textbox出问题了,断点调试下.
例子:
SqlConnection cn = new SqlConnection("server=(local);database=northwind;uid=sa;pwd=123");
SqlCommand cmd = cn.CreateCommand();
string str = "select count(*) from orders";
cmd.CommandText = str;
cn.Open();
string sum = cmd.ExecuteScalar().ToString();
cn.Close();
textBox1.Text = sum;另外补充一下,使用SqlDataAdapter 不需要显式打开,你原本打开的,它会保持打开,你原本关闭的,它会自动打开,然后在自动关闭。
建议你去看看sqlcommand和sqldataadapter的两种写法,应该为
SqlConnection cn = new SqlConnection("server=localhost;database=jtgl;user=sa;password=sa");
//SqlCommand cmd = new SqlCommand("select count(bltype) from ajd where bltype=1",cn);
SqlDataAdapter da = new SqlDataAdapter("select count(bltype) from ajd where bltype=1",cn);
DataSet ds = new DataSet();
da.Fill(ds, "ajd");
this.TextBox1.Text = ds.Tables[0].Rows[0][0].ToString()
SqlConnection cn = new SqlConnection("server=localhost;database=jtgl;user=sa;password=sa");
cn.Open();
//SqlCommand cmd = new SqlCommand("select count(bltype) from ajd where bltype=1",cn);
SqlDataAdapter da = new SqlDataAdapter("select count(bltype) from ajd where bltype=1",cn);
DataSet ds = new DataSet();
da.Fill(ds, "ajd");
this.TextBox1.Text = ds.Tables[0].Rows[0][0].ToString()
没看出来 不过adapter 是不用cn.open的 这点可以肯定
//select count(bltype) from ajd where bltype=1
//这个返回单个值 最好别使用SqlDataAdapter SqlCommand执行效果最好
cn.open();
SqlCommand cmd = new SqlCommand("select count(bltype) from ajd where bltype=1", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ajd");
cmd.dispose();
da.dispose();
cn.close(); this.TextBox1.Text = ds.Tables[0].Rows[0][0].ToString();
lz把代码写在点击事件里吧。。
TextBox1_TextChanged 这个事件谁知道你有没有触发他呀(楼上已经说过了)