填充Web表单编辑页面C#ASP.NET



我正在尝试在GridView上选择一个行,并让我将我带到带有数据填充的数据的单独编辑页面。我的想法是使用会话变量保存行ID,然后在页面加载上检索数据并填充文本框。我的问题是,这是否是这样做的最佳方法?我希望不使用GridView中的内联编辑选项,因为我有太多需要水平滚动的列。这是我的页面加载方法使用会话变量:

  if (Session["editID"] != null)
        {
            dbCRUD db = new dbCRUD();
            Recipe editRecipe = new Recipe();
            var id = Convert.ToInt32(Session["editID"]);
            Session.Remove("editID");

            editRecipe = db.SelectRecord(id);
            addName.Text = editRecipe.Name;
        }

这是用于检索行的SelectRecord方法:

 public Recipe SelectRecord(int id)
    {
        Recipe returnedResult = new Recipe();
            var dbConn = new SqlConnection(connString);
            var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn);

            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Parameters.Add("@ID", SqlDbType.Int).Value = id;

            dbConn.Open();
            SqlDataReader reader = dbCommand.ExecuteReader();
            while (reader.HasRows) 
            { 
                while (reader.Read())
                    {
                        returnedResult.Name = reader["Name"].ToString();
                    }
            }
            dbConn.Close();
            return returnedResult;
      }

我可能没有适当地使用SQLDATAREADER,但是我的结果是读者中没有数据,因此在调用该方法时没有返回的数据。任何帮助将不胜感激 - 预先感谢!

您应该在这里知道的几件事:

1。

如果存储过程返回多个结果集,则应使用while (reader.HasRows)。在这种情况下,您必须通过结果集迭代。请参阅使用DataReader检索数据。因此,如果selectRecipe返回多个结果集(我假设不是这种情况),请将您的代码更改为:

while (reader.HasRows) 
{ 
    while (reader.Read())
    {
        returnedResult.Name = reader["Name"].ToString();
    }
    reader.NextResult();
}


2。
如果selectRecipe返回单个结果集,请将WALE循环更改为if(){}

if(reader.HasRows) 
{ 
    while (reader.Read())
    {
        returnedResult.Name = reader["Name"].ToString();
    }
}


3。
我可能会使用using更好地管理连接(使用语句):

public Recipe SelectRecord(int id)
{
    Recipe returnedResult = new Recipe();
    using (SqlConnection dbConn = new SqlConnection(connString))
    {
        var dbCommand = new SqlCommand("dbo.selectRecipe", dbConn);
        dbCommand.CommandType = CommandType.StoredProcedure;
        dbCommand.Parameters.AddWithValue("@ID", id);
        dbConn.Open();
        SqlDataReader reader = dbCommand.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                returnedResult.Name = reader["Name"].ToString();
            }
        }
        reader.Close();
    }
    return returnedResult;
}

最新更新