4

そのため、グリッドビューで SQL テーブルの結果を表示しています。一部のフィールドは電話番号です。特定のフィールドは通常の 10 桁の数字ですが、4 桁の内線番号の場合もあります。4 桁の数字の場合は、少なくとも 10 桁の書式設定を適用したくありません。最大で、先頭に Ext: の後にデータを付けたいと思います。これが私がこれまでに持っているものです。私は通常プログラマーではないので、これは Visual Studio のウィザードと Google の結果を組み合わせたものです。ご協力いただきありがとうございます。

    <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>
4

1 に答える 1

1

次のように、電話番号が 10 桁か 4 桁かを判断し、ケースバイケースで各値を処理できるように、イベントを使用RowDataBoundしてグリッドにバインドされている各行をインターセプトする必要があります。

マークアップ:

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
     AutoGenerateColumns="False" onrowdatabound="GridView1_RowDataBound">

注:テキストを書式設定し、宣言ではなくイベントでプロパティを設定するため、 inText='<%# String.Format("{0:(###) ###-####}",Convert.ToInt64(DataBinder.Eval (Container.DataItem, "CallDestination")))%>'から を削除します。<asp:Label><ItemTemplate>TextRowDataBound

分離コード:

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;
            }
        }
    }
}
于 2013-08-28T14:12:25.927 に答える