gpt4 book ai didi

c# - 如何使用c#在asp.net中显示数据库中的数据

转载 作者:行者123 更新时间:2023-11-29 10:49:42 25 4
gpt4 key购买 nike

我试图根据用户输入的文本框的值显示来自 Mysql 数据库的数据,如下例所示

因为我是 ASP.NET 的初学者,所以我现在需要什么来显示该数据最快的方法是什么?

使用 div 或 table 标签进行布局哪个更好?

他们有更好的代码吗?就像使用标签来显示输出是个好主意吗?或者他们有更好的东西?

Image

代码标记

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AccountInquiry.aspx.cs" Inherits="BankingDemo.AccountInquiry" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Banking Site (Demo)</title>
</head>
<body>
<form ID="from" runat="server">
<div>
<asp:Label ID="lbl_ID" runat="server">Enter ID</asp:Label>
</div>

<asp:TextBox ID="ID" runat="server"></asp:TextBox>
<asp:Button ID="QurAcc" runat="server" Text="Query" OnClick="QurAcc_Click" />
<asp:Label ID="lbl_CityName" runat="server"></asp:Label>
</form>
</body>
</html>

c#代码

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.Configuration;
using MySql;
using MySql.Data;
using MySql.Data.Types;
using MySql.Data.MySqlClient;

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

public void get_info()
{
string connstr = ConfigurationManager.ConnectionStrings["ConnConfig"].ToString();
string cmdtxt = @"select Name,CountryCode,District,Population from world.city where id = @ID_param";
string temp = null;

try
{
using (MySqlConnection conn = new MySqlConnection(connstr))
using (MySqlCommand cmd = new MySqlCommand(cmdtxt))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID_param", ID.Text);
cmd.Connection = conn;
conn.Open();

MySqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
temp += "<br />";
temp += reader["Name"].ToString();
temp += reader["CountryCode"].ToString();
temp += reader["District"].ToString();
temp += reader["Population"].ToString();
temp += "<br />";
}
conn.Close();
}

lbl_CityName.Text = temp;
}
catch (Exception ex)
{
//ex.Message;
}
}

protected void QurAcc_Click(object sender, EventArgs e)
{
get_info();
}
}
}

最佳答案

正确的方法是创建四个标签,如下所示:

<br/>
<asp:Label ID="lblCityName" runat="server"></asp:Label>
<br/>
<asp:Label ID="lblCountry" runat="server"></asp:Label>
<br/>
<asp:Label ID="lblDistrict" runat="server"></asp:Label>
<br/>
<asp:Label ID="lblPopulation" runat="server"></asp:Label>

C#:

while (reader.Read())
{
lblCityName.Text = "Name: " + reader["Name"].ToString();
lblCountry.Text = "Country Code: " + reader["CountryCode"].ToString();
lblDistrict.Text = "District " + reader["District"].ToString();
lblPopulation.Text = "Population: " + reader["Population"].ToString();
}

关于c# - 如何使用c#在asp.net中显示数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43955514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com