当绑定字段binded_employer不存在时,如何处理GridView绑定错误?
解决GridView绑定不存在字段时的错误问题
这个问题我之前也碰到过,本质是当DataTable里没有binded_employer字段时,ASP.NET的绑定引擎找不到对应的属性,所以抛出了DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'binded_employer'这个错误。给你几个实用的解决思路:
方案一:绑定前动态控制列的可见性/移除列
如果某些场景下完全不需要这个字段,最直接的方式是在DataBind之前检查DataTable是否包含该字段,然后隐藏或者移除对应的TemplateField:
DataTable dt = new DataTable(); con.Open(); sqlArchiveData.Fill(dt); con.Close(); // 检查DataTable是否包含目标字段 if (!dt.Columns.Contains("binded_employer")) { // 假设你的TemplateField是GridView的第一列,根据实际索引调整 GridViewRaport.Columns[0].Visible = false; // 或者直接移除该列(如果后续也不需要的话) // GridViewRaport.Columns.RemoveAt(0); } GridViewRaport.DataSource = dt; GridViewRaport.DataBind();
这个方案的好处是完全避免了无效的绑定表达式执行,性能和安全性都比较好。
方案二:自定义绑定方法处理字段不存在的情况
如果你需要保留这个列,只是字段可能不存在,可以把绑定表达式改成调用后台的自定义方法,让方法来判断字段是否存在:
首先修改ASPX里的绑定代码:
<asp:TemplateField Visible="false"> <ItemTemplate> <asp:Label ID="customer_lbl" runat="server" Text='<%# GetFieldValue(Container.DataItem, "binded_employer") %>' Font-Size="10px" Visible="false"> </asp:Label> </ItemTemplate> </asp:TemplateField>
然后在后台代码(比如.aspx.cs文件)里添加这个方法:
protected string GetFieldValue(object dataItem, string fieldName) { DataRowView rowView = dataItem as DataRowView; if (rowView != null && rowView.Row.Table.Columns.Contains(fieldName)) { // 字段存在则返回对应值,注意处理DBNull的情况 return rowView[fieldName] == DBNull.Value ? string.Empty : rowView[fieldName].ToString(); } // 字段不存在返回空字符串或者默认值 return string.Empty; }
这里用类似Eval的思路(只做显示)代替了原来的Bind——如果你的场景不需要双向绑定(比如编辑功能),这个方案非常灵活;如果需要双向绑定,还是方案一更合适,因为Bind要求字段必须存在。
方案三:确保DataTable始终包含目标字段
另一种思路是从数据源层面解决,不管查询结果有没有这个字段,都手动给DataTable添加binded_employer列:
DataTable dt = new DataTable(); con.Open(); sqlArchiveData.Fill(dt); con.Close(); // 检查并添加字段 if (!dt.Columns.Contains("binded_employer")) { dt.Columns.Add("binded_employer", typeof(string)); // 给现有行设置默认值(可选) foreach (DataRow row in dt.Rows) { row["binded_employer"] = string.Empty; } } GridViewRaport.DataSource = dt; GridViewRaport.DataBind();
这个方案的好处是绑定表达式不需要修改,适合需要保持原有ASPX代码结构的场景。
内容的提问来源于stack exchange,提问作者Adriano
相关产品推荐
相关产品推荐

