ADO. NET отображение данных в GridView с использованием оператора SQL, C# - PullRequest
0 голосов
/ 05 апреля 2020

Я работаю с ADO. NET и подключаю базу данных к своему веб-сайту. Я пытаюсь отобразить данные из таблицы, которую я создал в SQL Server Management Studio, введя оператор SQL в текстовое поле. Это использует ASP. NET.

У меня есть текстовое поле, метка и кнопка. Мне удалось подключить мою базу данных к Visual Studio, но я не уверен, как отобразить данные, предоставив оператор SQL. До сих пор GridView с данными таблицы появляется автоматически, когда я открываю сайт. Однако я хочу, чтобы мой оператор SQL select * from StudentsTable отобразил его после того, как я поместил его в текстовое поле и нажал кнопку «Просмотр данных». Любое руководство будет с благодарностью.

Вот мой код до сих пор

HTML код:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DatabaseTest.aspx.cs" Inherits="DatabaseTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblHeading" runat="server" Text="Write your query below:"></asp:Label>
            <br />
            <br />
            <asp:TextBox ID="txtQuery" runat="server">
</asp:TextBox>
&nbsp;&nbsp;
            <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="View Data" />
            <br />
            <br />
            <asp:GridView ID="grdSqlData" runat="server" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" AutoGenerateColumns="False" DataKeyNames="StudentID" DataSourceID="SqlDataSource1">
                <Columns>
                    <asp:BoundField DataField="StudentID" HeaderText="StudentID" InsertVisible="False" ReadOnly="True" SortExpression="StudentID" />
                    <asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
                    <asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
                </Columns>
                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                <RowStyle BackColor="White" ForeColor="#330099" />
                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                <SortedAscendingCellStyle BackColor="#FEFCEB" />
                <SortedAscendingHeaderStyle BackColor="#AF0101" />
                <SortedDescendingCellStyle BackColor="#F6F0C0" />
                <SortedDescendingHeaderStyle BackColor="#7E0000" />
            </asp:GridView>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:StudentsConnectionString %>" SelectCommand="SELECT * FROM [StudentsTable] ORDER BY [StudentID], [FirstName]"></asp:SqlDataSource>
        </div>
    </form>
</body>
</html>

И код позади:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class DatabaseTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    // creating the connection object
    // ConfigurationManager.ConnectionStrings["sqlcon"].ToString()
    SqlConnection con = new SqlConnection(@"Data Source =CYBERPOWERPC\SQLEXPRESS; Initial Catalog = Students; Integrated Security = True");

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        con.Open();

        SqlCommand select_cmd = new SqlCommand();//command object
        select_cmd.CommandText = txtQuery.Text.ToString(); // specifying the command text retrieved from the text property of the text box
        select_cmd.Connection = con;

        lblHeading.Text = "Your query is: " + txtQuery.Text; //displaying the query in the label

        SqlDataReader reader = select_cmd.ExecuteReader(); //executing the command and reading into the data reader
        //  grdSqlData.DataSource = reader; //data source for the gridview - commented out because there were two definitions for grdSqlData
        grdSqlData.DataBind(); // binding data to gridview
    }
}

1 Ответ

0 голосов
/ 05 апреля 2020

Вам необходимо добавить источник данных в сетку. И источником данных будет результат, возвращаемый вашим запросом. Следуйте этому руководству: https://www.c-sharpcorner.com/article/display-data-in-a-datagridview-C-Sharp-6/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...