Найти несколько выпадающих списков в Gridview, заполненных отдельными SqlDatasources - PullRequest
0 голосов
/ 08 ноября 2018

Привет, ребята, поэтому у меня есть 4 выпадающих списка, каждый из которых назначен отдельным источникам данных SQL и помещен в сетку. Как показано ниже.

<asp:GridView ID="SupplierView" runat="server" OnRowDataBound="SupplierView_OnRowDataBound" OnPageIndexChanging="SupplierView_PageIndexChanging1" OnSorting="SupplierView_Sorting1" AllowPaging="True" AutoGenerateColumns="False" CssClass="GridCenter" CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center" OnRowUpdated="SupplierView_RowUpdated" OnRowUpdating="SupplierView_RowUpdating" ViewStateMode="Enabled"  >
              <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:BoundField DataField="MaterialNumber" HeaderText="Material Number" SortExpression="MaterialNumber" />
                <asp:BoundField DataField="MaterialDecsription" HeaderText="Material Description" SortExpression="MaterialDecsription" />
                <asp:TemplateField HeaderText="CountryOfOrigin" SortExpression="CountryOfOrigin">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CountryOfOrigin") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="CountryOfOriginDDL" runat="server"  SelectedValue='<%# Bind("CountryOfOrigin") %>' DataSourceID="SqlDataSource2COO" DataTextField="CountryOfOrigin" DataValueField="CountryOfOrigin" OnSelectedIndexChanged="CountryOfOriginDDL_OnSelectedIndexChanged" >
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ECCN" SortExpression="ECCN">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("ECCN") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="ECCNDDL" runat="server" DataSourceID="SqlDataSourceECCN" DataTextField="ECCN" DataValueField="ECCN" OnSelectedIndexChanged="ECCNDDL_OnSelectedIndexChanged"  ViewStateMode="Enabled" AutoPostBack="True">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ALCode" SortExpression="ALCode">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("ALCode") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="ALCODEDDL" runat="server" DataSourceID="SqlDataSourceALCODE" DataTextField="ALCode" DataValueField="ALCode" OnSelectedIndexChanged="ALCODEDDL_OnSelectedIndexChanged">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Preference" SortExpression="Preference">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Preference") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:DropDownList ID="PrefDDL" runat="server" DataSourceID="SqlDataSourcePREF" DataTextField="Preference" DataValueField="Preference" OnSelectedIndexChanged="PrefDDL_OnSelectedIndexChanged" AutoPostBack="True">
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>

              <EditRowStyle BackColor="#999999" />
              <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
              <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
              <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
              <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
              <SortedAscendingCellStyle BackColor="#E9E7E2" />
              <SortedAscendingHeaderStyle BackColor="#506C8C" />
              <SortedDescendingCellStyle BackColor="#FFFDF8" />
              <SortedDescendingHeaderStyle BackColor="#6F8DAE" />

        </asp:GridView>
                            <p>   <asp:Button ID="Updatebtn" runat="server" Text="Update" />-<asp:Button ID="Savebtn" runat="server" Text="Save"  />-<asp:Button ID="BtnLogOut" runat="server" Text="Log Out" OnClick="BtnLogOut_OnClick" />  </p>
                        </div>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SapMainServerDataPull %>" SelectCommand="SELECT [MaterialNumber], [MaterialDecsription], [CountryOfOrigin], [ECCN], [ALCode], [Preference] FROM [VendorDetailsRecordsForUpdate] WHERE ([VendorID] = @VendorID)">
            <SelectParameters>
                <asp:SessionParameter Name="VendorID" SessionField="VendorId" Type="String" />
            </SelectParameters>
                        </asp:SqlDataSource>


                        <asp:SqlDataSource ID="SqlDataSource2COO" runat="server" ConnectionString="<%$ ConnectionStrings:SapMainServerDataPull %>" SelectCommand="SELECT DISTINCT [CountryOfOrigin] FROM [VendorDetailsRecordsForUpdate] ORDER BY [CountryOfOrigin]" UpdateCommand="uspSupplierUpdateECCN" UpdateCommandType="StoredProcedure">
                            <UpdateParameters>
                                <asp:Parameter Name="ECCN" Type="String"></asp:Parameter>
                                <asp:Parameter Name="VendorId" Type="String"></asp:Parameter>
                            </UpdateParameters>
                        </asp:SqlDataSource>


        <asp:Label ID="ErrMsgUpdate" runat="server" Text=""></asp:Label>

                        <asp:SqlDataSource ID="SqlDataSourceECCN" runat="server" ConnectionString="<%$ ConnectionStrings:SapMainServerDataPull %>" SelectCommand="SELECT DISTINCT [ECCN] FROM [VendorDetailsRecordsForUpdate] ORDER BY [ECCN]" UpdateCommand="uspSupplierUpdateECCN" UpdateCommandType="StoredProcedure">
                            <UpdateParameters>
                                <asp:Parameter Name="ECCN" Type="String"></asp:Parameter>
                            </UpdateParameters>
                        </asp:SqlDataSource>
                        <asp:SqlDataSource ID="SqlDataSourceALCODE" runat="server" ConnectionString="<%$ ConnectionStrings:SapMainServerDataPull %>" SelectCommand="SELECT DISTINCT [ALCode] FROM [VendorDetailsRecordsForUpdate] ORDER BY [ALCode]"></asp:SqlDataSource>
                        <asp:SqlDataSource ID="SqlDataSourcePREF" runat="server" ConnectionString="<%$ ConnectionStrings:SapMainServerDataPull %>" SelectCommand="SELECT DISTINCT [Preference] FROM [VendorDetailsRecordsForUpdate] ORDER BY [Preference]"></asp:SqlDataSource>

Я новичок в кодировании (все еще на этапе обучения). Извините за простой вопрос.

на данный момент в раскрывающихся списках отображаются данные, которые мне нужны. Но после обратной передачи все они возвращаются к исходному значению, я провел небольшое исследование, и я считаю, что мне нужно сослаться на эти выпадающие списки в коде позади ... Я не хочу использовать адаптер sql и т. Д., Поскольку sqldatasource, кажется, работает по крайней мере, с указанием данных ..

Мне также нужно будет обновить приложение, для которого выбираются значения, поэтому как мне получить выпадающие списки для сохранения в базе данных после выбора?

Я также видел кое-что о связывании gridview вне постбэка при загрузке страницы. Извините, парень, я подозреваю, что это стандартные вещи, но опять же я не могу найти никакого реального решения моей конкретной проблемы. Я вижу много примеров sqldataadapter. и добавление значений с использованием списка, но я не хочу этого делать, так как значения могут меняться со временем, поэтому прямой вызов их из sqldatasource кажется логическим шагом.

это мой код до сих пор .. Большинство из них не работает, и я все на нем. Так что это, вероятно, не имеет особого смысла.

{
    public partial class Update : System.Web.UI.Page
    {
        public string Eccn { get; set; }
        public string CountryOfOrigin { get; set; }
        public string AlCode { get; set; }
        public string Pref { get; set; }

        public string VendorId;

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Session["VendorId"] != null)
                VendorId = Session["VendorId"].ToString();
            RefreshGrid(VendorId);

            if (Session["VendorId"] == null)
            {
                Response.Redirect("~/Login.aspx");
            }

            if (!IsPostBack)
            {
                BindGrid();
            }
        }
          public void RefreshGrid(string vendorId)
        {
            try
            {
                //get list of records from vendorId 
                BizManager biz = new BizManager();

                DataTable dt = new DataTable();

                biz.GetMaterialAndDesc(VendorId);

                SupplierView.DataSource = SqlDataSource1;
                SupplierView.DataBind();
            }
            catch (Exception ex)
            {
                ErrMsg = App.App.HandleError(MethodBase.GetCurrentMethod(), ex,
                    "Application Failed adding products to the list");
            }

        }


        private string ErrMsg
        {
            get { return ErrMsgUpdate.Text; }
            set { ErrMsgUpdate.Text = value; }
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }

            return newSortDirection;
        }

        protected void SupplierView_PageIndexChanging1(object sender, GridViewPageEventArgs e)
        {
            SupplierView.PageIndex = e.NewPageIndex;
            SupplierView.DataBind();
        }

        protected void SupplierView_Sorting1(object sender, GridViewSortEventArgs e)
        {
            DataTable dataTable = SupplierView.DataSource as DataTable;

            if (dataTable != null)
            {
                DataView dataView = new DataView(dataTable);
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

                SupplierView.DataSource = dataView;
                SupplierView.DataBind();
            }
        }

        private void RefreshData()
        {

        }

        protected void SupplierView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }

        protected void SupplierView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
        {

        }

        protected void BtnLogOut_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("~/Logout.aspx");
        }

        protected void CountryOfOriginDDL_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void ECCNDDL_OnSelectedIndexChanged(object sender, EventArgs e)
        {

            DropDownList ddl = sender as DropDownList;

            foreach (GridViewRow row in SupplierView.Rows)
            {
                Control ctrl = row.FindControl("ECCNDDL") as DropDownList;
                if (ctrl != null)
                {
                    DropDownList ddl1 = (DropDownList) ctrl;

                    if (ddl.ClientID == ddl1.ClientID)
                    {
                        SqlDataSourceECCN.UpdateParameters["VendorId"].DefaultValue = "0000107898";
                        SqlDataSourceECCN.UpdateParameters["ECCN"].DefaultValue = ddl1.SelectedValue;
                    }
                }
            }

            //Session["VendorId"] = VendorId;

            //SqlDataSourceECCN.UpdateParameters["VendorId"].DefaultValue = Session.ToString();
            //SqlDataSourceECCN.UpdateParameters["ECCN"].DefaultValue = Eccn;


        }

        protected void ALCODEDDL_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void PrefDDL_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void SupplierView_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                DropDownList dropDownLst = (DropDownList)e.Row.FindControl("ECCNDDL");

                dropDownLst.DataSource = SqlDataSourceECCN;

                dropDownLst.DataTextField = "ECCN";
                dropDownLst.DataValueField = "ECCN";
                dropDownLst.DataBind();



              }
            }
        }
    }

1 Ответ

0 голосов
/ 08 ноября 2018

В веб-формах мне просто накачать некоторые DataTables для хранения данных. Поэтому я использую простой метод, чтобы получить данные из базы данных и вернуть DataTable с результатом. Запрос может быть процедурой выбора или хранимой процедурой.

public static DataTable LoadDataFromDB(string query)
{
    DataTable dt = new DataTable();

    using (SqlConnection connection = new SqlConnection(ConnectionString))
    using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
    {
        try
        {
            adapter.Fill(dt);
        }
        catch
        {
        }
    }

    return dt;
}

Теперь вы можете использовать LoadDataFromDB везде, чтобы просто заполнить элементы управления данными.

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack == false)
    {
        //as a query
        DataTable dt = LoadDataFromDB("select top 10 * from mytable");
        GridView1.DataSource = dt;
        GridView1.DataBind();

        //or stored procedure
        DropDownList1.DataSource = LoadDataFromDB("mysp 1, 2");
        DropDownList1.DataTextField = "columnA";
        DropDownList1.DataValueField = "columnB";
        DropDownList1.DataBind();
    }
}

UPDATE

То, что они находятся в GridView, не имеет значения. Просто используйте FindControl.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList ddl = e.Row.FindControl("") as DropDownList;

        ddl.DataSource = LoadDataFromDB("select a from b order by c");
        ddl.DataTextField = "username";
        ddl.DataValueField = "fullwidth";
        ddl.DataBind();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...