【发布时间】:2019-04-19 15:31:52
【问题描述】:
using System;
using System.Data.SqlClient;
namespace car_database
{
public partial class WebForm1 : System.Web.UI.Page
{
public class car
{
string connstring = "Data Source=.\\SqlExpress; Initial Catalog=carsale; Integrated Security=True";
protected BtnView(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(connstring);
try
{
myConnection.Open();
string query = "select model ,price from car where Id =@carid";
SqlCommand mycmd = new SqlCommand(query, myConnection);
int carid1;
if (!int.TryParse(TextBox1.Text, out carid1))
{
Label1.Text = "please enter a numeric ID!";
}
else
{
mycmd.Parameters.Add("@carid", System.Data.SqlDbType.Int);
mycmd.Parameters["@carid"].Value = carid1;
SqlDataReader reader = mycmd.ExecuteReader();
if (reader.Read())
{
Label1.Text = "Model:" + reader["model"] + "<br/>" + "price:" + (string)reader["price"];
}
else
{
Label1.Text = "no car has this id ";
}
reader.Close();
}
}
catch (Exception ex)
{
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = ex.Message;
}
finally
{
myConnection.Close();
}
}
}
}
}
我想根据TextBox1中输入的Id,在点击按钮时在Label1中显示车型和价格。
aspx 标记:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="car_database.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
enter id to retrieve the model and the price of the car :
<asp:TextBox runat="server" ID="TextBox1" />
<br />
<asp:Button runat="server" ID="btn" OnClick ="BtnView" />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
但代码不起作用 - 我收到一些错误:
公车必须有返回类型
TextBox1.Text 和 Label1.Text 有错误:
非静态字段方法或属性需要对象引用
【问题讨论】:
-
protected BtnView(object sender, EventArgs e)应该是protected void BtnView(object sender, EventArgs e) -
从基础开始:docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…。您的代码有几个问题。一个类中的按钮点击方法,一个没有返回的类T...
标签: c# asp.net sql-server visual-studio express