C# 在ASP.NET中发布GridView

C# 在ASP.NET中发布GridView,c#,c#-code-model,C#,C# Code Model,我只想知道最后两行的区别 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) if (GridView1.Rows[e.RowIndex].RowType == DataControlRowType.DataRow) { GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex]; string lstnme = (

我只想知道最后两行的区别

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 if (GridView1.Rows[e.RowIndex].RowType == DataControlRowType.DataRow)
  {
   GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

   string lstnme = ((TextBox)row.Cells[2].FindControl("txtLstNme")).Text;


没有区别,但我建议在指定文本值之前检查控件是否为null

string lstnme = string.Empty;
var control = ((TextBox)row.Cells[2].FindControl("txtLstNme"));
if ( control != null )
{
     lstnme = control.Text
}
  • string lstnme=((TextBox)row.Cells[2].FindControl(“txtlsnme”).Text
    基本上是指在单元格中查找名为txtlsnme的控件,然后返回textbox控件内的文本

  • string lstnme=((TextBox)row.Cells[2].控件[0]).Text
    这意味着lstnme将在单元格中的位置0处保存控件文本


  • 主要区别在于第一个是在控件的列表集合中查找文本框,但第二个是在位置0处获取控件的文本。

    两个输出的结果是否有任何差异取决于您是否在该位置存在,如果它在同一位置存在[定位然后相同的输出,否则输出将明显不同。请检查错误“无法将类型为'System.Web.UI.DataBoundLiteralControl'的对象强制转换为类型为'System.Web.UI.WebControl.TextBox',并且只有一个名为'TXTLSNME'的文本框。这不是真的,这是不同的。如果有两个文本框控件并选择控件[0]然后您可能无法获得所需的对象。请检查错误“无法将类型为'System.Web.UI.DataBoundLiteralControl'的对象强制转换为类型为'System.Web.UI.WebControls.TextBox',并且只有一个名为'txtlsnme'的文本框
    string lstnme = string.Empty;
    var control = ((TextBox)row.Cells[2].FindControl("txtLstNme"));
    if ( control != null )
    {
         lstnme = control.Text
    }