网格视图格式字段为电话号码,但有些结果是4位数的扩展,如何处理
本文关键字:扩展 何处理 处理 4位 结果是 字段 格式 视图 电话号码 网格 | 更新日期: 2023-09-27 18:29:31
所以我在gridview中显示SQL表的结果。有些字段是电话号码。一个特定的字段可以是一个正常的10位数字,但也可以是4位的扩展名。如果它是一个4位数的数字,我至少不想在上面加上10位数的格式,最多我想在它前面加上Ext:然后加上我的数据。这是我迄今为止所拥有的。我通常不是程序员,所以这是Visual Studio向导和谷歌结果拼凑而成的。非常感谢您的帮助。
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Call Destination" SortExpression="CallDestination">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("CallDestination") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# String.Format("{0:(###) ###-####}",Convert.ToInt64(DataBinder.Eval (Container.DataItem, "CallDestination")))%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:OnCallConnectionString %>" SelectCommand="SELECT [TimeStamp], [CallerID], [Accepted], [CallDestination] FROM [OnCallLog]"></asp:SqlDataSource>
</div>
</form>
您需要使用RowDataBound
事件来拦截绑定到网格的每一行,这样您就可以确定电话号码是10位还是4位,并根据具体情况处理每个值,如下所示:
标记:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound">
注意:从<ItemTemplate>
中的<asp:Label>
中删除Text='<%# String.Format("{0:(###) ###-####}",Convert.ToInt64(DataBinder.Eval (Container.DataItem, "CallDestination")))%>'
,因为您将格式化文本并在RowDataBound
事件中设置Text
属性,而不是声明式设置。
代码背后:
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
// Only interested in each data row, not header or footer, etc.
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the Label2 control in the row
Lable theLabel = (Label)e.row.FindControl("Label2");
// Make sure control is not null
if(theLabel != null)
{
// Cast the bound to an object we can use to extract the value from
DataRowView rowView = (DataRowView)e.Row.DataItem;
// Get the value for CallDestination field in data source
string callDestinationValue = rowView["CallDestination"].ToString();
// Find out if CallDestination is 10 digits or 4 digits
if(callDestinationValue.Length == 10)
{
theLabel.Text = String.Format("{0:(###) ###-####}", Convert.ToInt64(rowView["CallDestination"]));
}
if(callDestinationValue.Length == 4)
{
theLabel.Text = "Ext: " + callDestinationValue;
}
}
}
}