【问题标题】:My GridView will not populate with data from my SQL datasource我的 GridView 不会填充来自我的 SQL 数据源的数据
【发布时间】:2015-12-17 19:20:43
【问题描述】:

我创建了一个绑定到本地 SQL 数据库文件 (mdf) 的 GridView。数据库连接成功。我确实收到了来自我的 EmptyDataText="No Data" 的错误消息,该错误消息位于 GridView 所在的网页上。

任何帮助将不胜感激。

这是我持有 GridView 的 div:

   <div style="border: 10px hidden #0B4A80; height: 108px; width: 494px; overflow: auto; margin-bottom: 40px;" >
    <asp:SqlDataSource runat="server" ID="SqlDataSource1" 
      ConnectionString='<%$ ConnectionStrings:DefaultConnection %>' 
      SelectCommand="SELECT AspNetUsers.EmailConfirmed, AspNetUser.UserName, AspNetUsers.FirstName, AspNetUsers.LastName, AspNetUsers.BusinessName, AspNetRoles.Name FROM AspNetUsers INNER JOIN AspNetRoles ON AspNetUsers.Id = AspNetRoles.Id INNER JOIN AspNetUserRoles ON AspNetUsers.Id = AspNetUserRoles.UserId AND AspNetRoles.Id = AspNetUserRoles.RoleId"></asp:SqlDataSource>
    <asp:GridView ID="GridView2" runat="server" SelectMethod ="" UpdateMethod ="" AutoGenerateColumns="true" DataKeyNames="Id" EmptyDataText="No Data" EnableModelValidation="false" ForeColor="#333333" GridLines="None" BorderStyle="None" BorderWidth="10px" Height="75px" PageSize="3" Width="472px">
      <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
      <Columns>
        <asp:BoundField DataField="Text" HeaderText="User Information" />
        <asp:DynamicField DataField="EmailConfirmed" HeaderText="EmailConfirmed" SortExpression="EmailConfirmed"></asp:DynamicField>
        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName"></asp:BoundField>
        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"></asp:BoundField>
        <asp:DynamicField DataField="BusinessName" HeaderText="Business Name" SortExpression="BusinessName"></asp:DynamicField>
        <asp:DynamicField DataField="UserName" HeaderText="Email" SortExpression="UserName"></asp:DynamicField>
        <asp:DynamicField DataField="Name" HeaderText="Role"  SortExpression="Role" ></asp:DynamicField>
       </Columns>
      <EditRowStyle BackColor="#999999" />
      <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
      <HeaderStyle BackColor="#D7E4FF" Font-Bold="True" ForeColor="#1484AA" />
      <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
      <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
      <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />          
    </asp:GridView>
  </div>

这是我的代码:

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      BindGrid1();
      BindGrid2();
    }

      private void BindGrid2()
      {
        String queryString = "SELECT [EmailConfirmed], [UserName], [FirstName], [LastName], [BusinessName], [Name] FROM AspNetUsers INNER JOIN AspNetRoles ON AspNetUsers.Id = AspNetRoles.Id INNER JOIN AspNetUserRoles ON AspNetUsers.Id = AspNetUserRoles.UserId AND AspNetRoles.Id = AspNetUserRoles.RoleId";
        DataSet ds = GetData(queryString);
        if (ds.Tables.Count > 0)
        {
          GridView2.DataSource = ds;
          GridView2.DataBind();
        }
        else
        {
          Response.Write("Unable to conenct to the database");
        }

      }

      DataSet GetData(String queryString)
      {
        //Retrive the connection string in the web.config file.
        String connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

        DataSet ds = new DataSet();

        try
        {
          // Connect to the database and run query.
          SqlConnection connection = new SqlConnection(connectionString);
          SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

          //Fill the dataSet.
          adapter.Fill(ds);
        }
        catch(System.Exception ex)
        {
          // The connection failed. Display an error message.
          Response.Write("Unable to connect to the database.");
          Response.Write(ex.Message);
        }
        return ds;
      }
   }
}

【问题讨论】:

    标签: c# sql gridview webforms asp.net-4.5


    【解决方案1】:

    请删除您的代码隐藏数据库调用。您已经从 ASPX 页面的 SQL 数据源填充了 gridview。

    ASPX:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1">
      <Columns>
          <asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
          <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
          <asp:CheckBoxField DataField="EmailConfirmed" HeaderText="EmailConfirmed" SortExpression="EmailConfirmed" />
          <asp:BoundField DataField="PasswordHash" HeaderText="PasswordHash" SortExpression="PasswordHash" />
          <asp:BoundField DataField="SecurityStamp" HeaderText="SecurityStamp" SortExpression="SecurityStamp" />
          <asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
          <asp:CheckBoxField DataField="PhoneNumberConfirmed" HeaderText="PhoneNumberConfirmed" SortExpression="PhoneNumberConfirmed" />
          <asp:CheckBoxField DataField="TwoFactorEnabled" HeaderText="TwoFactorEnabled" SortExpression="TwoFactorEnabled" />
          <asp:BoundField DataField="LockoutEndDateUtc" HeaderText="LockoutEndDateUtc" SortExpression="LockoutEndDateUtc" />
          <asp:CheckBoxField DataField="LockoutEnabled" HeaderText="LockoutEnabled" SortExpression="LockoutEnabled" />
          <asp:BoundField DataField="AccessFailedCount" HeaderText="AccessFailedCount" SortExpression="AccessFailedCount" />
          <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
          <asp:BoundField DataField="TrialExpiration" HeaderText="TrialExpiration" SortExpression="TrialExpiration" />
          <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
      </Columns>
    </asp:GridView>
    
    <asp:SqlDataSource runat="server" ID="SqlDataSource1" 
    ConnectionString='......' SelectCommand="SELECT AspNetUsers.EmailConfirmed, AspNetUser.UserName, AspNetUsers.FirstName, AspNetUsers.LastName, AspNetUsers.BusinessName, AspNetRoles.Name FROM AspNetUsers LEFT OUTER JOIN AspNetUserRoles ON AspNetUsers.Id = AspNetUserRoles.UserId LEFT OUTER JOIN AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId"></asp:SqlDataSource>
    

    C# 代码隐藏:

    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }
    }
    

    【讨论】:

    • 是的,我正在使用 Identity。我仍然收到“无数据”错误消息。当我使用“创建数据源”向导时,创建了原始的 Select 语句。我刚刚用你的 Select 语句再次运行了这个。当我选择“文本查询”时,只返回列标题。我在 AspNetUser 表中有一个注册用户。
    • @joey.coyle 我不明白你的意思。 SQL 在对数据库执行时是否返回任何记录?
    • @joey.coyle 你在AspNetRolesAspNetUserRoles 表中有记录吗?
    • 如果我对项目中的 AspNetUser 表执行“显示表数据”,则会返回一条记录。我只是无法让这条记录显示在我的 GridView 中。如果我通过转到设计视图并在我的数据源对象上选择“配置数据源”来编辑我的项目中的选择语句。有一个选项可以测试查询语句。当我这样做时,只返回列标题。我假设我应该看到我的一个记录。
    • @joey.coyle 我已经更新了我的 SQL 语句,你可以试试并告诉我。
    【解决方案2】:

    您忘记打开连接了吗?

     using(SqlConnection connection = new SqlConnection(connectionString))
     {
          connection.Open();
          SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
    
          //Fill the dataSet.
          adapter.Fill(ds);
     }
    

    【讨论】:

    • 我在这里添加了你的代码,没有任何影响。我仍然没有数据。我认为与数据源的连接不是问题。
    猜你喜欢
    • 2020-07-14
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2020-08-13
    • 1970-01-01
    • 2011-08-18
    • 2020-05-03
    相关资源
    最近更新 更多