我有一个数据库。我在sqlcommand中从数据库中获取两个值,但我面临的一个问题是如何从reader()中的表中获取adminstatus ..
我的代码
protected void signin_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand comm = new SqlCommand("SELECT password,adminstatus FROM usertable WHERE userid = @username", conn))
{
comm.Parameters.AddWithValue("@username", logintext.Text);
conn.Open();
using (SqlDataReader reader = comm.ExecuteReader())
{
if (reader.Read())
{
string password = reader.GetString(0);
//int st =Convert.ToInt32(reader.GetString(1));
//int st = reader.GetInt32(0);
if (password == logpasstext.Text)
{
Session["userid"] = logintext.Text;
// iframestyle.Attributes["src"] = "userpage.aspx";
iframestyle.Attributes["src"] = "userpage.aspx";
logdiv.Attributes["style"] = "display:none;";
}
/* else if (password == logpasstext.Text && st == 1)
{
Session["userid"] = logintext.Text;
// iframestyle.Attributes["src"] = "userpage.aspx";
iframestyle.Attributes["src"] = "adminpage.aspx";
logdiv.Attributes["style"] = "display:none;";
}*/
else
{
errorsignin.Visible = true;
errorsignin.Text = "INVALID LOGIN";
logdiv.Attributes["style"] = "display:block;";
}
}
else
{
errorsignin.Visible = true;
errorsignin.Text = "INVALID LOGIN";
logdiv.Attributes["style"] = "display:block;";
}
}
}
}
我无法使用阅读器从表中获取adminstatus ...
答案 0 :(得分:1)
尝试将string indexer
与SQLDataReader一起使用。只需指定要撤消的列名称
string adminstatus= Convert.ToString(reader["AdminStatus"]);
// Assuming AdminStatus is a column name
答案 1 :(得分:0)
string adminStatus = reader.GetString(1)
其中" 1"是查询中字段的位置
或更好:
string adminStatus = reader.GetString(reader.GetOrdinal("adminstatus"))
reader.GetOrdinal("adminstatus")
返回查询中字段的位置
你必须更换" GetString"使用与数据类型对应的方法(例如,GetInt32或GetFloat或GetBoolean)
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
答案 2 :(得分:0)
您可以使用reader.GetOrdinal(ColumnName)
来避免幻数。
然后我去
//if adminstatus is a SQL string like the other field
reader.GetString(reader.GetOrdinal("adminstatus")); // returns string
//if adminstatus is for example a SQL bit
reader.GetBoolean(reader.GetOrdinal("adminstatus")); // returns bool