以下程序从SQL Server 2008表中提取数据后,应用简单的for循环并计算记录总数。程序编译并成功运行,没有任何错误,但不会打印到屏幕的记录总数。它不会打印任何东西。 .cs(代码隐藏)是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
namespace CountDocs
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCount_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd = new SqlCommand())
{
String sql = "select * from dbo.Company";
cmd.Connection = con;
cmd.CommandText = sql;
con1.Open();
Int32 Total = 0;
Total = (Int32)cmd1.ExecuteScalar();
Console.WriteLine(Total);
if (con.State == ConnectionState.Open)
{
con.Close();
}
for (int i = 0; i < dt.Rows.Count; ++i)
{
string companyname;
companyname = dt.Rows[i].ItemArray[0].ToString();
SqlConnection con1 = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd1 = new SqlCommand())
{
String sql1 = "select Count(*) from dbo.Documents where Src=" + "'" + companyname + "'";
cmd1.Connection = con1;
cmd1.CommandText = sql1;
con.Open();
DataTable dt1 = new DataTable();
Int32 Total = 0;
Total = (Int32)cmd1.ExecuteScalar();
Console.WriteLine(Total);
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
}
}
}
}
}
}
由于程序没有抛出任何语法错误,我想这可能是一个逻辑错误。有人可以告诉我吗?提前致谢。
答案 0 :(得分:1)
系统工作正常,因为如果你写 dt1.Rows [0] .ToString(),你就没有得到单元格的值。这是因为System.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem.Data.DataRowSystem不会覆盖方法 ToString()。
我认为您必须使用dt1.Rows[0].ItemArray[3]
或dt1.Rows[0]["column name"].ToString();
希望这有帮助。