Как сохранить значение текстовых полей, используя TemplateFields в GridView - PullRequest
0 голосов
/ 03 июля 2019

У меня есть GridView, в котором перечислены данные из моей таблицы базы данных mysql. Кроме того, я создал два TemplateFields для GridView. Первый TemplateField отображает данные из таблиц базы данных, а второй TemplateView содержит 1x asp: TextBox (также называемое количество) и 2x asp: Buttons (также называемые кнопками +/-, которые изменяют значение внутри TextBox. В дополнение к привязке GridView на PageLoad Событие, у меня также есть поиск TextBox, который фильтрует строки, отображаемые в GridView. Вот код для поиска GridView TextBox:

private void SearchProducts()
    {


        string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            using (MySqlCommand cmd = new MySqlCommand())
            {
                string sql = "SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products";
                if (!string.IsNullOrEmpty(txtSearch.Text.Trim()))
                {
                    sql += " WHERE description LIKE " + "'%" + txtSearch.Text + "%'";


                }
                cmd.CommandText = sql;
                cmd.Connection = con;
                using (MySqlDataAdapter sda = new MySqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    GridView1.DataSource = dt;

                   dt.Columns.Add(new DataColumn("QUANTITY"));


                    GridView1.DataBind();
                    //TextBox qty4 = GridView1.FindControl("qty_ordered") as TextBox;





        //      for(int i = 0; i < GridView1.Rows.Count; i++)
        //{
        //                 Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
        //    TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
        //    if (ViewState["purchased"] != null)
        //    {
        //        qty2.Text = ViewState["purchased"].ToString();
        //    }
        //    //test222.Text = qty2.Text;
        //}







                }
            }
        }







           //foreach(GridViewRow rows in GridView1.Rows)
                   {


                  //Label test22 = rows.FindControl("test2") as Label;
                 //TextBox qty = rows.FindControl("qty_ordered") as TextBox;
            //if (ViewState["purchased"] != null)
            //{
                //qty.Text = ViewState["purchased"].ToString();
            //}


            }




        }

Сначала я попытался сохранить все строки TextBox.Text в ViewState, но безуспешно, затем я попытался динамически добавить новый столбец в DataTable перед DataBind (), но он также пошел на юг ... Кнопки (+/-) и TextBox отлично работает, когда PostBack от самих кнопок. Однако, как только я отфильтрую GridView, используя приведенный выше код c #, все текстовые поля возвращаются в «0» и теряют свои значения. Я думаю, что динамическое добавление нового столбца - это путь, я просто не уверен, как сохранить / обновить значения без создания EditTemplateFields.

Вот мой код asp.net для GridView:

<asp:GridView id="GridView1" EnableViewState="true"  AutoGenerateColumns="false" PageSize="100" ShowHeader="false" DataKeyNames="logic_code" AllowPaging="true" runat="server" Style="width:100%;margin-top:45px;">
<Columns>


<asp:BoundField DataField="QUANTITY" runat="server" readonly="true" />

<asp:TemplateField HeaderText="Product_Template" runat="server"> 


<ItemTemplate>
<asp:label id="supplier_number" runat="server" Style="font-weight:bold;font-size:28px;" Text='<%# Eval("supplier_number")%>' /> <asp:label id="total_inventory" runat="server" Text='<%# Eval("total_inventory")%>' Style="float:right;" />
<br />
<asp:label id="sequence" runat="server" Text='<%# Eval("sequence")%>' Style="float:right;" />
<br />
<asp:Image id="product_image" runat="server" Height="320px" Width="320px" ImageUrl='<%# Eval("image_location")%>' />
<br />
<asp:label id="product_description" runat="server" Text='<%# Eval("description")%>' Style="white-space:nowrap;" /> &nbsp<asp:label id="unit_of_price" runat="server" Text='<%# Eval("unit_of_price")%>' Style="float:right;font-size:10px;margin-top:16px;margin-right:5px;margin-left:1px;" /><asp:label id="price_pref" runat="server" Text='<%# "$" + Eval("price_pref")%>' Style="float:right;font-size:22px;font-weight:bold;" /> 
</ItemTemplate>

</asp:TemplateField>   
<asp:TemplateField HeaderText="Product_Template1" runat="server" ItemStyle-Width="150px"> 


<ItemTemplate runat="server">
<asp:Button id="add" runat="server"  Text="+" Width="45px" Style="float:right;" OnClick="addClicked" autopostback="true" UseSubmitBehavior="true"></asp:Button> <asp:Button id="subtract" runat="server" Text="-" Style="float:right;" OnClick="subtractClicked" autopostback="true" UseSubmitBehavior="true" Width="45px"></asp:Button>
<asp:TextBox id="qty_ordered" runat="server" Text="0" Enabled="false" Style="float:right;" Width="57px" EnableViewState="true" ReadOnly="true" />

<asp:Label id="unit_display" runat="server" Style="float:right;" />

<asp:Label id="sequenceID" runat="server" Text='<%# Eval("sequence")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_code1" runat="server" Text='<%# Eval("unit_code")%>' Visible="false" Enabled="false" />
<asp:Label id="supplier_no" runat="server" Text='<%# Eval("supplier_number")%>' Visible="false" Enabled="false" />
<asp:Label id="total_inventory1" runat="server" Text='<%# Eval("total_inventory")%>' Visible="false" Enabled="false" />
<asp:Label id="logic_code1" runat="server" Text='<%# Eval("logic_code")%>' Visible="false" Enabled="false" />
<asp:Label id="unit_of_price1" runat="server" Text='<%# Eval("unit_of_price")%>' Visible="false" Enabled="false" />
<asp:Label id="price_pref1" runat="server" Text='<%# Eval("price_pref")%>' Visible="false" Enabled="false" />
<asp:Label id="special_price1" runat="server" Text='<%# Eval("special_price")%>' Visible="false" Enabled="false" />
<asp:Label id="description1" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="tester" runat="server" Text='<%# Eval("description")%>' Visible="false" Enabled="false" />
<asp:Label id="test2" runat="server" Visible="true" Enabled="false" />


</ItemTemplate>

</asp:TemplateField>   




</Columns>
</asp:GridView>

Вот код для того, как я заполняю GridView в PageLoad, когда GridView не фильтруется окном поиска:

private void BindGrid()
    {

    string constr = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
            con.Open();
                using (MySqlCommand cmd = new MySqlCommand("SELECT logic_code,description,image_location,product_group,supplier_number,sequence,unit_code,unit_of_price,location,sales_date,price_pref,special_price,in_stock,total_inventory,new_products FROM products"))
                {
                    using (MySqlDataAdapter da = new MySqlDataAdapter())
                    {
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        using (DataTable dt = new DataTable())
                        {
                            da.Fill(dt);
                            GridView1.DataSource = dt;
                            dt.Columns.Add(new DataColumn("QUANTITY", System.Type.GetType("System.Double")));

                            GridView1.DataBind();
                        con.Close();


                        }
                    }
                }
            }


    }

И PageLoad здесь:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            BindGrid();
        }






        if (string.IsNullOrEmpty(txtSearch.Text))
        {
        //txtSearch.Attributes.Add("CssStyle", "cursor");
            txtSearch.Attributes.Add("placeholder", " Showing All Products");
        }


        //foreach(GridViewRow row in GridView1.Rows)
        //{
        //    if (IsPostBack)
        //    {
        //        if (ViewState["purchased"].ToString() != null)
        //        {
        //            qty.Text = ViewState["purchased"].ToString();
        //        }
        //    }
        //}


    }

У меня также есть EnableViewState = "true" вверху страницы.

*** Примечание: с кодом, приведенным ниже на каждой кнопке (+/-), ViewState, похоже, отлично сохраняет свои данные, так как мои метки заполняются надлежащим образом, читая ViewState, даже при обратной передаче. Однако значения меток (значение ViewState) сбрасываются, когда я вызываю private void SearchProducts()

for(int i = 0; i < GridView1.Rows.Count; i++)
        {
                         Label test222 = (Label)GridView1.Rows[i].FindControl("test2");
            TextBox qty2 = (TextBox)GridView1.Rows[i].FindControl("qty_ordered");
            ViewState["purchased"] = qty2.Text;
            test222.Text = ViewState["purchased"].ToString();
        }

и вот 2 снимка: (как вы можете видеть, когда я ввожу «Benus» в текстовое поле поиска, представление сетки корректно фильтруется, но все значения TextBox сбрасываются в «0»)

BindGrid() and addClicked/subtractClicked events

SearchProducts()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...