我有以下用于搜索表格中文本的方法
protected void fillGridView(int followingID, string text)
{
SqlCommand myCommand = new SqlCommand("select t.*,u.firstName,u.lastName,u2.firstName as afirstName,u2.lastName as alastName ,i.icon,ii.iconPath as taskIcon, iii.iconPath as seenIcon,f.fileName,f.fileID from tasks as t inner join users as u on u.userID=t.addedBy inner join users as u2 on u2.userID=t.attachTo inner join priorityIcons as i on t.priority=i.priorityID inner join icons as ii on t.status=ii.iconName inner join icons as iii on t.isNew=iii.iconName left join files as f on t.fileID=f.fileID where t.followingID=@followingID and t.firstName LIKE '%asd%'");
myCommand.Parameters.AddWithValue("@followingID", followingID);
myCommand.Parameters.AddWithValue("@text", text);
DBAccess db = new DBAccess();
DataSet ds = db.select(myCommand);
SqlDataAdapter adapter = new SqlDataAdapter();
tasksRepeater.DataSourceID = null;
tasksRepeater.DataSource = ds.Tables[0]; //Here the exception appear because the dataset ds is "null"
tasksRepeater.DataBind();
tasksCounter();
}
异常消息是“对象引用未设置为对象的实例。”
但是当我用上面的sql语句交换sql语句时,代码运行成功
SqlCommand myCommand = new SqlCommand("select t.*,u.firstName,u.lastName,u2.firstName as afirstName,u2.lastName as alastName ,i.icon,ii.iconPath as taskIcon, iii.iconPath as seenIcon,f.fileName,f.fileID from tasks as t inner join users as u on u.userID=t.addedBy inner join users as u2 on u2.userID=t.attachTo inner join priorityIcons as i on t.priority=i.priorityID inner join icons as ii on t.status=ii.iconName inner join icons as iii on t.isNew=iii.iconName left join files as f on t.fileID=f.fileID where t.followingID=@followingID");
那么问题是什么!?
答案 0 :(得分:0)
您的查询未返回任何行,因此当您执行ds.Tables[0]
时,它会抛出,因为ds.Tables
为空。
我怀疑您的查询有拼写错误,因为您正在设置@text
参数的值,但查询中不存在该参数。您的查询可能需要以:
"...where t.followingID=@followingID and t.firstName LIKE '%@text%'"
话虽这么说,你的代码应该能够处理查询没有返回任何行的情况(你可以通过检查ds.Tables
上的Count
属性来检查这一点。)
答案 1 :(得分:0)
我猜错误在where子句中。请尝试使用此查询
"select t.*,u.firstName,u.lastName,u2.firstName as afirstName,u2.lastName as alastName ,i.icon,ii.iconPath as taskIcon, iii.iconPath as seenIcon,f.fileName,f.fileID from tasks as t inner join users as u on u.userID=t.addedBy inner join users as u2 on u2.userID=t.attachTo inner join priorityIcons as i on t.priority=i.priorityID inner join icons as ii on t.status=ii.iconName inner join icons as iii on t.isNew=iii.iconName left join files as f on t.fileID=f.fileID where t.followingID=@followingID and u.firstName LIKE '%asd%'"
输入u.FirstName而不是t.firstName。
我猜错误是t的别名。
试试这个。