收藏 dataGridView 未将对象引用设置到对象的实例
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 LibraryCRM
{
public partial class ReaderInfo : Form
{
public ReaderInfo()
{
InitializeComponent();
}
private void ReaderInfo_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“libraryCRMDataSet7.Reader”中。您可以根据需要移动或删除它。
this.readerTableAdapter.Fill(this.libraryCRMDataSet7.Reader);
}
private void button2_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count>0)
{
if (MessageBox.Show("确定要删除该行数据吗?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
string conStr = "Server= USERSWO-MI8QI4Q\\SQLEXPRESS;Initial Catalog=LibraryCRM;Integrated Security=SSPI";
SqlConnection conn = new SqlConnection(conStr);
int index = this.dataGridView1.CurrentCell.RowIndex;
string readerID = this.dataGridView1.Rows[index].Cells["readerIDDataGridViewTextBoxColumn"].Value.ToString();
string strSQL = "Delete From Reader Where readerID= '" + readerID + "'";
try
{
conn.Open();
SqlCommand cmd =new SqlCommand ();
cmd = conn.CreateCommand();
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
strSQL = "SELECT * FROM Reader ";
SqlDataAdapter sda = new SqlDataAdapter(strSQL, conn);
DataSet ds = new DataSet();
sda.Fill(ds, "Reader");
dataGridView1.DataSource = ds.Tables["Reader"];//出错点
MessageBox.Show("成功删除数据!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null)
conn.Close();
}
}
}
else
{
MessageBox.Show("没有读者数据存在!");
}
}
}
}
一执行到 dataGridView1.DataSource = ds.Tables["Reader"];就出现“System.NullReferenceException”类型的未经处理的异常出现在 System.Windows.Forms.dll 中的错误 --------------------编程问答-------------------- T T 有没有人能解答下 --------------------编程问答-------------------- NullReferenceException 就是值为空,查询到的数据为空,是不是你前面只有一条数据,然后被你删除了,表中就没有数据了 --------------------编程问答-------------------- Try ExecuteScalar.
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
}
补充:.NET技术 , .NET Framework