是实现从数据库查询数据的。。
请看代码
public partial class Form2 : Form
{
private DataSet ds; //声明Dataset
private SqlDataAdapter bs; //声明读取年级信息的数据适配器
string saih = "Data Source=.;Initial Catalog=ri;Integrated Security=True";
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{ //调用方法
searchstudent();
}
public void searchstudent()
{ //创建数据库链接
SqlConnection conn = new SqlConnection(saih);
try
{ //查询年级的SQL语句
StringBuilder sb = new StringBuilder();
sb.Append("select id,name,sex,birthday");
sb.Append(" from grade");
if (Convert.ToInt32(this.cbo.SelectedValue) != -1)
{
sb.AppendFormat(" where id={0}",Convert.ToInt32(this.cbo.SelectedValue));
}
sb.Append(" order by [id]");
bs = new SqlDataAdapter(); //填充Dataset
SqlCommand comm = new SqlCommand(sb.ToString(),conn);
bs.SelectCommand = comm;
//填充钱,清空原有的数据
if (ds.Tables["grade"] != null)
{
ds.Tables["grade"].Clear();
}
bs.Fill(ds, "grade");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"异常提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
finally
{
conn.Close();
}
}
private void btnselect_Click(object sender, EventArgs e)
{
searchstudent();
}
}
}
结果显示:未将对象引用设置到对象的实例
我们现在学的还是些简单的基础东西。。这些代码我是按照书本上敲的。过程没有报错什么的。但是运行就是没效果。请各位帮帮忙
我们学的和你的不一样,但我想问你一下 , 你的代码中怎么没有把数据绑定到datagridview(这个控件的单词可能打错了),可能就是这个原因吧,我也是新手,你们没老师教吗?