我尝试将我的sql连接移动到类文件中的方法并返回一个值以检查db中是否存在用户名并在页面中显示为文本以向其他人显示用户名存在。我应该如何修改我的aspx .cs页面以在aspx代码页中显示错误作为标签?
我在aspx .cs页面上的原始代码:
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";
我的班级文件代码:
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;
}
我的aspx cs文件中的代码:
MemberDB.searchusername(UNameTxtBox.Text);
答案 0 :(得分:2)
在您的网页中添加 <?php
$arr = array(
array('type'=>'ORANGE', 'attribute'=>'sweet'),
array('type'=>'ORANGE', 'attribute'=>'tropical'),
array('type'=>'BANANA', 'attribute'=>'yellow')
);
$new = array();
foreach($arr as $a) {
$out[$a['type']]['attribute'][] = $a['attribute'];
}
$new = array();
foreach($out as $key=>$val) {
$new[]= array('type'=>$key,$val);
}
unset($out);
echo "<pre>";
var_dump($new);die;
?>
,并通过该方法将标签的label
属性设置为Text
value
。
returned
而且在背后的代码中这样做
<asp:Label runat="server" ID="userExists"></asp:Label>
答案 1 :(得分:0)
public static bool searchusername(string username)
{
connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(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;
}
return exists;
}
在您的信息页
中if(MemberDB.searchusername(UNameTxtBox.Text))
{
ExistLabel.Text = "UserName exists";
}