[英]System.InvalidCastException: Specified cast is not valid at .ExecuteScalar
I'm working on an app linked to a local database. 我正在开发一个链接到本地数据库的应用程序。 What I want, is to show in a form datae from database, but in labels.
我想要的是在数据库中以数据形式显示,但在标签中显示。 I created a list of labels, but I get this error at command.Executescalar(), where I try to get the number of rows entered in the dataBase, so the list can create the exact number of rows.
我创建了一个标签列表,但是在command.Executescalar()处出现此错误,在这里我尝试获取在数据库中输入的行数,因此该列表可以创建确切的行数。 Thanks !
谢谢 !
int infoCount = (int)command.ExecuteScalar();
var pozitie = 50; //50 pixeli
for (var i = infoCount ; i >= 0; i--)
{
//creez si adaug un nou label in form
Label label = new Label();
label.Text = dataTable.Rows[i][i].ToString();
label.Location = new Point(pozitie, 150);
label.AutoSize = true;
//afisez in form
//adaug in colectie
labels.Add(label);
} }
LE: LE:
var query = "SELECT * FROM grupe WHERE Nume='" + nume + "'";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
This query returns not the number of records: 该查询不返回记录数:
SELECT * FROM grupe WHERE Nume=@nume
Instead it selects all columns, with ExecuteScalar
it returns the value of the first row's first column. 而是选择所有列,并使用
ExecuteScalar
返回第一行第一列的值。 Instead you want to use: 相反,您想使用:
SELECT COUNT(*) FROM grupe WHERE Nume=@nume
Also use sql-parameters (as shown above) to prevent sql injection. 还可以使用sql-parameters(如上所示)来防止sql注入。
using(var command = new SqlCeCommand(query, conn))
{
command.Parameters.Add("@nume", SqlDbType.VarChar).Value = nume;
}
Also note that indices are zero based in C#, so you access the first item in a list or array via coll[0]
. 另请注意,在C#中,索引基于零,因此您可以通过
coll[0]
访问列表或数组中的第一项。 The last item is at coll.Count-1
For that reason you should change your for loop to: 最后一项是
coll.Count-1
。因此,您应该将for循环更改为:
for (int i = infoCount - 1 ; i >= 0; i--)
{
// ...
}
But you don't need to determine the row-count with a separate query at all. 但是,您根本不需要使用单独的查询来确定行数。 You are filling a
DataTable
which has a table.Rows.Count
property. 您正在填充具有
table.Rows.Count
属性的DataTable
。 So it's easy: 这样很简单:
// ...
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
for(int i = dataTable.Rows.Count - 1; i >= 0; i--)
{
DataRow row = dataTable.Rows[i];
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.