我再次收到错误,说明没有与SQL查询匹配的行。
它声明:
位置0没有行。
要点:
firstnameTxt.Text = dt.Rows[0].ItemArray[1].ToString();
以下是我的C#代码。
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] != null)
{
redPnl.Visible = false;
UserNameSess.Text += Session["New"].ToString();
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Student_Username, Student_FName, Student_SName, Student_Email FROM Student Where Student_Username=@StuUsername", con);
sda.SelectCommand.Parameters.Add("@StuUsername", SqlDbType.VarChar).Value = UserNameSess.Text;
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
usernameTxt.Text = dt.Rows[0].ItemArray[0].ToString();
firstnameTxt.Text = dt.Rows[0].ItemArray[1].ToString();
surnameTxt.Text = dt.Rows[0].ItemArray[2].ToString();
emailTxt.Text = dt.Rows[0].ItemArray[3].ToString();
dt.Clear();
}
else
{
redPnl.Visible = true;
}
}
我不知道它为什么这么做,因为它诚实地带回了价值并在文本框中显示它。
答案 0 :(得分:5)
您忘了在您的if
子句中添加大括号:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["New"] != null)
{
redPnl.Visible = false;
UserNameSess.Text += Session["New"].ToString();
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select Student_Username, Student_FName, Student_SName, Student_Email FROM Student Where Student_Username=@StuUsername", con);
sda.SelectCommand.Parameters.Add("@StuUsername", SqlDbType.VarChar).Value = UserNameSess.Text;
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
usernameTxt.Text = dt.Rows[0].ItemArray[0].ToString();
firstnameTxt.Text = dt.Rows[0].ItemArray[1].ToString();
surnameTxt.Text = dt.Rows[0].ItemArray[2].ToString();
emailTxt.Text = dt.Rows[0].ItemArray[3].ToString();
dt.Clear();
}
}
else
{
redPnl.Visible = true;
}
}
答案 1 :(得分:3)
您需要将if
下的语句用一对{}
括起来,否则该条件将仅应用于下一个语句;其他人将照常执行
if (dt.Rows.Count > 0)
{
usernameTxt.Text = dt.Rows[0].ItemArray[0].ToString();
firstnameTxt.Text = dt.Rows[0].ItemArray[1].ToString();
surnameTxt.Text = dt.Rows[0].ItemArray[2].ToString();
emailTxt.Text = dt.Rows[0].ItemArray[3].ToString();
}
如果根据条件只需要执行一个语句,则可以省略{}
,在所有其他情况下,您应该将语句括在{}