简体   繁体   English

错误:位置 0 没有行如何修复

[英]ERROR: There is no row at position 0 how to fix it

This image is where after user login, they will be able to see their account details.此图像是用户登录后,他们将能够查看其帐户详细信息的位置。

This image is another small form that allows the user to change the username.此图像是另一种允许用户更改用户名的小表单。

Currently, the error is when after changing the username.目前,错误是在更改用户名后。 When it directed back to a page in image 1, it crashes.当它返回到图像 1 中的页面时,它崩溃了。

public void showdata()
{
    cmd.CommandText = "Select * from Registration where Username='" + Session["user"] + "'";
    cmd.Connection = con;
    sda.SelectCommand = cmd;
    sda.Fill(ds);

    lblUsername.Text = ds.Tables[0].Rows[0]["Username"].ToString();// error occur at here. 
    lblEmail.Text = ds.Tables[0].Rows[0]["Email"].ToString();
    lblName.Text = ds.Tables[0].Rows[0]["Fullname"].ToString();
    lblContact.Text = ds.Tables[0].Rows[0]["Contactnumber"].ToString();
    lblPassword.Text = ds.Tables[0].Rows[0]["Password"].ToString();
}

I do not understand this error.我不明白这个错误。 The error is there is no row at position 0.错误是位置 0 处没有行。

There is no row at position 0 - that means your result set is empty and you need to check count before access any row.位置 0 处没有行- 这意味着您的结果集为空,您需要在访问任何行之前检查计数。

if (ds.Tables == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) {
    // Throw the error or retrun the code 
}

Note:笔记:

  • Need to handle null every time before getting value from Session.每次从 Session 获取值之前都需要处理 null。 You can create a custom class for handling all sessions for that.您可以创建一个自定义类来处理所有会话。 Refer this link for Custom Class 有关自定义类,请参阅此链接
  • Before getting value from row also need to handle NULL.在从行获取值之前还需要处理 NULL。 like use below method喜欢使用下面的方法

    public static T GetValueFromDataRow<T>(this DataRow row, string columnName) { if (row.Table.Columns.Contains(columnName) && (object)row[columnName] != DBNull.Value) { return (T)row[columnName]; } return default; }

You need to verify that rows exist before attempting to get data from them.在尝试从中获取数据之前,您需要验证行是否存在。

if (ds.Tables[0].Rows.Count > 0){
    // Fetch the data... 
}
else
{
    // Handle missing data or show some friendly message 
}

在 Change() 函数中,没有代码更新 Session["user"] 中的用户名,因此可能发生的情况是您的 SELECT 命令仍在使用以前的用户名,因此返回 0 行。

In showdata() function is you are sending Session["user"] as username value, which you have not set in Change() function .在 showdata() 函数中,您正在发送Session["user"]作为用户名值,您尚未在Change()函数中设置该值。

So, in Change() function,to get the updated value first set因此,在 Change() 函数中,首先要获取更新的值

Session["user"]= txtuserchange.Text

Please check and confirm.请检查并确认。

请确保您的 Session["user"] 具有有效数据和查询返回列表或注册对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM