I am new to C#. Just following Kudvenkat tutorials for beginners. I get an error on this line:
SqlDataReader rdr = cmd.ExecuteReader();
Something to do with ExecuteReader();
I am sure its something simple, but could you please explain why does it happens?
My aspx.cs file
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();
}
}
}
}
My aspx file:
<%@ 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>
SqlDataReaderjust the same as the official one, which C# don't know which you are usingvar rdr = cmd.ExecuteReader();or better:System.Data.SqlClient.SqlDataReader rdr = cmd.ExecuteReader();. Of course the best practice is to rename your namespace as @Prisoner suggests.