返回从SQL值 [英] Return a value from sql
问题描述
我试着移动在类文件中我SQL连接的方法和返回值来检查用户名在DB和显示在页面文字现有的向人展示该用户名存在。我应该如何修改我的aspx页面的.cs显示错误作为ASPX code页面?
标签在ASPX页面的.cs对我原先的code:
字符串的ConnectionString = ConfigurationManager.ConnectionStrings [myConnectionString]的ConnectionString。
使用(SqlConnection的CON =新的SqlConnection(的connectionString))
{
con.Open(); 布尔存在= FALSE; //创建一个命令来检查是否存在用户名
使用(CMD的SqlCommand =新的SqlCommand(SELECT COUNT(*)会员其中UserName = @UserName,CON))
{
cmd.Parameters.AddWithValue(用户名,UNameTxtBox.Text);
存在=(int)的cmd.ExecuteScalar()> 0;
} //如果存在,显示错误消息
如果(存在)
ExistLabel.Text =用户名存在;
我的类文件code:
公共静态字符串searchusername(字符串的用户名)
{
的connectionString = ConfigurationManager.ConnectionStrings [myConnectionString]的ConnectionString。
康涅狄格州的SqlConnection =新的SqlConnection(的connectionString);
{
conn.Open(); 布尔存在= FALSE; 使用(COMM的SqlCommand =新的SqlCommand(会员SELECT COUNT(*),其中UserName = @UserName,康涅狄格州))
{
comm.Parameters.AddWithValue(@用户名的用户名);
存在=(int)的comm.ExecuteScalar()> 0;
}
如果(存在)
{
回到存在;
}
返回null;
}
而code在我的aspx文件CS:
MemberDB.searchusername(UNameTxtBox.Text);
在您的网页添加标签
并设置文本
标签的属性设置为值
返回
的方法。
< ASP:标签=服务器ID =userExists>< / ASP:标签>
和超过code背后做这样的
userExists.Text = MemberDB.searchusername(UNameTxtBox.Text);
Im trying move my sql connection to a method in a class file and return a value to check if the username existing in the db and display as text in the page to show others that the username exist. How should i modify my aspx .cs page to display error as a label in the aspx code page?
My original code on the aspx .cs page:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
bool exists = false;
// create a command to check if the username exists
using (SqlCommand cmd = new SqlCommand("select count(*) from Member where UserName = @UserName", con))
{
cmd.Parameters.AddWithValue("UserName", UNameTxtBox.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
// if exists, show a message error
if (exists)
ExistLabel.Text = "UserName exists";
My class file code:
public static string searchusername(string username)
{
connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
{
conn.Open();
bool exists = false;
using (SqlCommand comm = new SqlCommand("select count(*) from Member where UserName = @UserName", conn))
{
comm.Parameters.AddWithValue("@username", username);
exists = (int)comm.ExecuteScalar() > 0;
}
if (exists)
{
return "exist";
}
return null;
}
And the code in my aspx cs file:
MemberDB.searchusername(UNameTxtBox.Text);
Add a label
in your page and set the Text
property of label to the value
returned
by the method.
<asp:Label runat="server" ID="userExists"></asp:Label>
And than in code behind do like this
userExists.Text = MemberDB.searchusername(UNameTxtBox.Text);
这篇关于返回从SQL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!