我是C#的新手。只为初学者学习Kudvenkat教程。我在这一行有个错误:
SqlDataReader rdr = cmd.ExecuteReader();与ExecuteReader();有关的事情
我肯定事情很简单,但你能解释一下为什么会发生这种事吗?
我的aspx.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace SqlDataReader
{
public partial class SqlDataReader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// creating variable that holds value of connection string
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
// creating connection object with use of "using" block
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select top 5 ProductID, LocationID,Shelf,Quantity from [Production].[ProductInventory]", con);
SqlDataReader rdr = cmd.ExecuteReader(); // --Error
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}我的aspx文件
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SqlDataReader.aspx.cs" Inherits="SqlDataReader.SqlDataReader" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</form>
</body>
</html>发布于 2017-02-01 04:34:39
因为您的类和名称空间的名称,编译器假设rdr的类型是SqlDataReader,这是名称空间SqlDataReader下的类名。所以这里最好的选项是重命名您的类,替代选项也是完全限定名。这意味着您必须在实例化类时指定类的命名空间,即代码将如下所示:
System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader(); // No Error now对于您来说,另一个选项是使用静态类型定义器,使用该类型的var将被自动分配以存储我们正在辅助它们的值,即:
var rdr = cmd.ExecuteReader(); // No Error now在这里,rdr将是ExecuteReader()方法正在重新运行的类型。
https://stackoverflow.com/questions/41971908
复制相似问题