当我没有为登录用户定义 Usertype
时,我的 Gridview 工作正常。现在我的 BindGrid()
函数无法正常工作,并给我错误信息
System.InvalidOperationException: ExecuteReader: CommandText property has not been initialized Error is coming
下面是我的 BindGrid 代码:-
protected void BindGrid()
{
string username = string.Empty;
string usertype = string.Empty;
try
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT usertype,username FROM tbl_User WHERE username='" + Session["User"].ToString() + "'", conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
username = dr["username"].ToString();
usertype = dr["usertype"].ToString();
}
}
conn.Close();
string query = string.Empty;
if (usertype == "0") // superadmin
{
query = "select Id,username,email,usertype,active,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User ORDER By Id DESC";
}
if (usertype == "1") // admin
{
query = "select Id,username,email,usertype,active,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User WHERE usertype != '0' ORDER By Id DESC";
}
if (usertype == "2") // user
{
query = "select Id,username,email,usertype,active,(CASE WHEN usertype='1' THEN 'Admin' WHEN usertype='0' THEN 'Super Admin' WHEN usertype='2' THEN 'User' END) AS UserRoleName from tbl_User WHERE username='" + username + "' ORDER By Id DESC";
}
cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grdUser.DataSource = ds.Tables[0];
grdUser.DataBind();
}
catch (Exception)
{
throw;
}
}
请指出这里有什么问题。
最佳答案
我推荐以下内容:
- Implement your code with the
using
statement - Use parameterized SQL
- 确保您的初始查询返回一条记录且仅返回一条记录(您的循环将仅捕获最后遇到的
username
和usertype
) - Implement the
switch
statement and ensure proper handling of thedefault
case - 确保您的连接已为您的第二个 SQL 查询打开
- 如果您只是重新抛出异常,则不需要 try/catch block 。
关于c# - 系统.InvalidOperationException : ExecuteReader: CommandText property has not been initialized Error is coming,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28943744/