![](/img/trans.png)
[英]How to call a method from aspx.cs to another aspx.cs in same project?
[英]Haw to call method from class to aspx.cs
班级代码:
using System.Data.SqlClient;
namespace WebApplication5
{
public class Class1
{
public int ID;
public string nem;
public int salar;
public void ReadIMP(int id )
{
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=emp;Integrated Security=True");
string Query = "select * from employee where Id = '" + id + "' ";
SqlCommand cmd = new SqlCommand(Query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ID = (int)reader["Id"];
nem = (string)reader["name"];
salar = (int)reader["salary"];
}
reader.Close();
conn.Close();
}
}
}
aspx.cs代码:
protected void Read_IMP(object sender, EventArgs e)
{
try
{
Class1 class1 = new Class1();
class1.ReadIMP(Convert.ToInt16(TextBox1.Text));
}
catch (Exception ex)
{
LabelEX.Text = ex.Message;
}
}
aspx代码:
<div>
enter the id of employees :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Id of employees is
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
name of employees is
<asp:Label ID="Label2" runat="server"></asp:Label>
<br />
salary of employee is :
<asp:Label ID="Label3" runat="server"></asp:Label>
<asp:Button ID="Button4" runat="server" Text="Search" OnClick="Read_IMP" />
<br />
<asp:Label ID="LabelEX" runat="server" Text="Label"></asp:Label>
.................................................. ....................................我在类中使用方法从数据库中检索数据,并在所需的aspx.cs页面中调用该方法来填充以下属性:ID,nem,salar到Label1,Label2,Label3中我可以这样做吗
从代码中,您已经在字段中填充了数据,然后将这些数据直接填充到aspx
控件中
Class1 class1 = new Class1();
class1.ReadIMP(Convert.ToInt16(TextBox1.Text));
Label1.Text = (string)class1.ID;
Label2.Text = class1.nem;
Label3.Text = (string)class1.salar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.