0

目前,我几乎没有接受GridView对象作为参数的方法,并且GridView正在访问对象中的值以执行计算。

我的问题是这是否是一个好习惯?我注意到,当我需要更改结果显示时(即GridView最初将有 9 个单元格而不是 10 个单元格的结果),我需要更改所有使用它的方法,否则可能会ArrayIndexOutOfBound出错。

例子

public static string checkCount(GridView gr)
{
     //need to change the cell index if the sql to get the gridview is changed
     string name = gr.Rows[b].Cells[9].Text.ToUpper(); 
}

对此有什么想法吗?

谢谢

编辑
最好有一种方法将 sql 结果映射到对象列表中,其中对象本身是数据行的表示。这样即使我删除了一个列,我只需要处理映射方法本身,其他的应该按照规范运行。

例子:

public class Profile{
    string name {get;set;}
    string icNo {get;set;}
}

public list getProfileList(){
    //run some query here and loop the result
    //while looping
    profile = new Profile(name=/*the name result*/, icNo=/*icNo from result*/ );
    //return the list
}

页面加载

List profiles = getProfileList();
gv.DataSource = profiles;
gv.DataBind();


public string calculationMethod(List profiles){
    //when in need of the result, just get the object from profiles and process
}
4

2 回答 2

1

对象作为参数,并且正在访问 GridView 对象中的值以执行计算

价值观从何而来?我认为更好的做法是直接在您的数据/业务对象或仅负责此特定计算的帮助对象上执行计算。然后你可以有另一个函数从这个帮助对象而不是你的 BO 或其他东西动态创建结果视图。

将有 9 个单元格而不是最初的 10 个单元格的结果

这正是您不应该直接使用单元格进行计算的原因。如果你真的需要这样做,那么你应该寻找另一种方法来找到计算的索引。它们可能取决于实际的结果对象。(其中您的值也可以出现在特定的数据类型中;仅用于可视化和用户输入,应转换为字符串或类似的)

一般来说,要解决这个问题,您应该清楚地分析您的需求是什么。保留一些东西,例如:

也可以考虑为您的应用程序使用 n-Tier 模型

于 2012-09-10T09:37:53.560 回答
0

转换<asp:BoundField><asp:TemplateField>

<asp:TemplateField HeaderText="name" SortExpression="DateCreated">
      <ItemTemplate>
             <asp:label id="LbMyName" text="" runat="server">
      </ItemTemplate>
</asp:TemplateField>

现在您可以从后面的代码中调用:

Label lb = GridView1.Rows[i].FindControl("LbMyName");
于 2012-09-10T21:40:58.453 回答