0

デバッグ中に、上記の奇妙なエラーが発生しました。私のドロップダウンリストはDropDownlist1と呼ばれているので、それは奇妙でした. 以前と同じに設定すると、デバッガーは文字列にキャストできないと言いました。

だからここに問題がある私のC#があります。

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
       Gridsource.ConnectionString = "Data Source=CATALOGSERVER;Initial Catalog=UACOrders;Persist Security Info=True;User ID=Catalog;Password=pass";
        Gridsource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
        Gridsource.SelectCommand = "GetOrderHistory";
        Gridsource.DataSourceMode = SqlDataSourceMode.DataSet;
        GridView1.DataSource = Gridsource;

        ControlParameter cp = new ControlParameter();
        cp.ControlID = DropDownList1.ClientID;
        cp.Name = "Company";
        cp.PropertyName = "SelectedValue";
        cp.Type = System.TypeCode.String;
        Gridsource.SelectParameters.Add(cp);
        Gridsource.Page = this;
        this.Controls.Add(Gridsource);
        GridView1.DataBind();
        updatepanel1.Update();
 }

そして、ここに関連するasp.netの小さな部分があります

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="contentarea">     
    <asp:ScriptManager runat="server"></asp:ScriptManager>
    <asp:UpdatePanel runat="server" ChildrenAsTriggers="true" UpdateMode="Conditional" ID="updatepanel1">
        <ContentTemplate>

            <div>
                <asp:Label Text="Company: " runat="server"></asp:Label>
                <asp:DropDownList ID="DropDownList1" runat="server"
                     DataSourceID="company" DataTextField="COMPANY" DataValueField="COMPANY" 
                    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
                     AutoPostBack="true" >
                </asp:DropDownList>
                <asp:SqlDataSource ID="company"
                     runat="server" ConnectionString="<%$ ConnectionStrings:UACOrdersConnectionString %>"
                     SelectCommand="SELECT [Customer] AS [COMPANY] FROM [Accounts] ORDER BY [Customer]">
                </asp:SqlDataSource>
                <asp:SqlDataSource ID="Gridsource" runat="server"></asp:SqlDataSource>

奇妙なことに、この種のことをasp.netコードで正常に機能させることができます。しかし、この特定の Web ページが必要とする C# コードビハインドで動作させることができないようです。繰り返しになりますが、実際には cp.ControlID が何と等しいかを調べる必要があります。

具体的な例外は「InvalidOperationException was unhandled by user code.」です。「ControlParameter 'Company' にコントロール 'DropDownList1' が見つかりませんでした。」

VSは39行目に例外を置きます。

         GridView1.DataBind();

さらにコードを表示する必要がある場合は、コメントを残してください。さらに投稿します。

4

2 に答える 2

1

質問の更新されたコードに基づいて、DropDownList と SqlDataSource (この ControlParameter が属する) が同じネーミング コンテナーにないことが問題であることがわかります。いくつかのオプションがあります。

  1. コード ビハインドでのみ作成し、ページ ライフサイクルの後半で追加するのではなく、SqlDataSource をマークアップに追加します。これは最も簡単なオプションです。
  2. SqlDataSource を Page.Controls コレクションに、ページ ライフサイクルの早い段階でプログラムによって追加します。Init イベント中のように。

このような:

protected void Page_Init(object sender, EventArgs e)
{
    Page.Controls.Add(Gridsource);
}
于 2013-07-03T19:04:42.490 に答える