You need to use the RowDataBound event to intercept each row, since it is tied to the grid, so you can determine if the phone number is 10 digits or 4 digits and process each value in each case, for example:
Markup:
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound">
Note. Remove Text='<%# String.Format("{0:(###) ###-####}",Convert.ToInt64(DataBinder.Eval (Container.DataItem, "CallDestination")))%>' from <asp:Label> to <ItemTemplate> because you format the text and set the Text property to RowDataBound instead of declarative.
Code for:
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; } } } }
source share