Чтение данных из таблицы и добавление в текстовое поле - PullRequest
0 голосов
/ 03 апреля 2019

Как я могу прочитать данные из сетки? Я хочу добавить содержимое столбца OrderLinePrice и добавить в текстовое поле итоговую цену заказа? Я хочу, чтобы все это происходило, когда я нажимал кнопку «Добавить в заказ» (чтобы обновить общую стоимость заказа)

Я думаю - «для каждой строки сложите каждое значение столбца OrderLinePrice вместе», возможно, я мог бы включить эту формулу в кнопку расчета цены заказа

Код моей кнопки добавления в заказ:

protected void AddToOrderBtn_Click(object sender, EventArgs e)
    {
        try
        {
            // this code will insert the data the user has inputted
            string connectionString;
            SqlConnection cnn;

            connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            cnn = new SqlConnection(connectionString);

            cnn.Open();
            Response.Write("Connection Made");
            SqlCommand command;
            SqlDataAdapter adapter = new SqlDataAdapter();

            String sql = "";
            sql = "INSERT INTO[OrderLine](OrderLineID, OrderID, ProductID, OrderLineQuantity, OrderLinePrice) Values('" + Convert.ToInt32(OrderLineIDTB.Text) + "','" + Convert.ToInt32(OrderIDTB.Text) + "','" + Convert.ToInt32(ProductIDTB.Text) + "', '" + Convert.ToInt32(OrderLineQuantityTB.Text) + "', '" + Convert.ToDecimal(ProdPriceTB.Text)*Convert.ToInt32(OrderLineQuantityTB.Text) + "')";
            command = new SqlCommand(sql, cnn);
            adapter.InsertCommand = new SqlCommand(sql, cnn);
            adapter.InsertCommand.ExecuteNonQuery();

            command.Dispose();



            cnn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("error" + ex.ToString());
        }

        string connectionString1;
        SqlConnection cnn1;

        connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        cnn1 = new SqlConnection(connectionString1);
        string selectSql1 = "SELECT * FROM [OrderLine]";
        SqlCommand com1 = new SqlCommand(selectSql1, cnn1);

        try
        {
            cnn1.Open();

            using (SqlDataReader read = com1.ExecuteReader())
            {
                while (read.Read())
                {
                    int orderlineidmax = Convert.ToInt32(read["OrderLineID"]);
                    orderlineidmax++;
                    OrderLineIDTB.Text = orderlineidmax.ToString();
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("error" + ex.ToString());
        }
        finally
        {
            cnn1.Close();
        }


        try
        {
            SqlConnection cnn2 = new SqlConnection("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");

            cnn2.Open();
            SqlCommand command1 = new SqlCommand("SELECT * FROM OrderLine WHERE OrderID = ('" + Convert.ToInt32(OrderIDTB.Text) + "') ", cnn2);
            SqlDataReader reader = command1.ExecuteReader();
            OrderDetailsGridView.DataSource = reader;
            OrderDetailsGridView.DataBind();
            cnn2.Close();

        }
        catch (Exception ex)
        {
            Response.Write("error" + ex.ToString());
        }

    }

application

Ответы [ 2 ]

0 голосов
/ 03 апреля 2019

Я нашел решение, изменив ответ на другой вопрос, см. Ответ

Код моей кнопки для расчета общей стоимости:

private decimal ordersubtotal;

    protected void CalcPriceBtn_Click(object sender, EventArgs e)
    {

        string connectionString1;
        SqlConnection cnn1;

        connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
        cnn1 = new SqlConnection(connectionString1);
        string selectSql1 = "SELECT * FROM [OrderLine] WHERE OrderID = ('" + Convert.ToInt32(OrderIDTB.Text) + "')";
        SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
        ordersubtotal = 0.0M;
        try
        {
            cnn1.Open();


            using (SqlDataReader read = com1.ExecuteReader())
            {

                while (read.Read())
                {

                    decimal rowtotal = Convert.ToDecimal(read["OrderLinePrice"]);
                    ordersubtotal += rowtotal;

                }

            }
        }
        catch (Exception ex)
        {
            Response.Write("error" + ex.ToString());
        }
        finally
        {
            cnn1.Close();
            OrderPriceTB.Text = ordersubtotal.ToString();
            CreateOrderBtn.Visible = true;
        }
    }
0 голосов
/ 03 апреля 2019

Получение суммы сразу после этого:

 OrderDetailsGridView.DataSource = reader;
 OrderDetailsGridView.DataBind();
 cnn2.Close();
 GetTotal();//Code added to your textbox

public void GetTotal()
    {
        double Total = 0;
        foreach (GridViewRow r in OrderDetailsGridView.Rows)
        {
            Total = Total + double.Parse(r.Cells[4].Text); // double check if this is the orderline price
        }
        YourTextBox.Text = Total.ToString();
    }

Примечание. Этот код еще не проверен.

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