Search code examples
c#sql-serverado.netreturnexecutescalar

How to use ExecuteScalar() to get a value and give it to your textbox.text?


this is my table:

CREATE TABLE [dbo].[InvoiceTable] (
    [Id]                 INT           IDENTITY (1, 1) NOT NULL,
    [CodeColumn]         NVARCHAR (50) NOT NULL,
    [NameColumn]         NVARCHAR (50) NOT NULL,
    [QTYColumn]          INT           NULL,
    [TotalQTYColumn]     INT           NULL,
    [UnitCostColumn]     INT           NOT NULL,
    [DiscountRateColumn] FLOAT (53)    DEFAULT ((0)) NULL,
    [RowTotalColumn]     AS            (([QTYColumn]*[UnitCostColumn])*((1)-[DiscountRateColumn])) PERSISTED,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

I have an Invoice form and a Confirimation form. User selects the desired goods in the first form and confirms how much he/she should pay in the second form. I want my program to show the value of sum(RowTotalColumn) as a text in my TotalCostTextBox.Text. I wrote the following code:

private int ConfirmForm_Load(object sender, EventArgs e)
{
    string selectQuery = "SELECT Sum(RowTotalColumn) FROM InvoiceTable";
    var sqlcmd = new SqlCommand(selectQuery, sqlcon);
    var result = sqlcmd.ExecuteScalar();
    return int.Parse(result.ToString());
    TotalCostTextBox1.Text = result.ToString();

when I put TotalCostTextBox1.Text = result.ToString(); after return it yells

Unreachable code detected

when I put it before return, TotalCostTextBox1 shows nothing...

Please tell me how to fill the TotalCostTextBox1 with the value. not about return statement.


Solution

  • You need to place below assignment statement before return

    TotalCostTextBox1.Text = result.ToString();
    

    Your final code should be like below code:

    private void ConfirmForm_Load(object sender, EventArgs e)
    {
        string selectQuery = "SELECT Sum(RowTotalColumn) FROM InvoiceTable";
        var sqlcmd = new SqlCommand(selectQuery, sqlcon);
        var result = sqlcmd.ExecuteScalar();
        TotalCostTextBox1.Text = result.ToString();
        //return int.Parse(result.ToString());
    }
    

    Also you need to check the event binding with ConfirmForm_Load function. To verify this please check if following line is available in ConfirmForm.Designer.cs

    this.Load += new System.EventHandler(this.ConfirmForm_Load);