Question How to assign a value to a databound textbox?

surajlk

New member
Joined
Apr 24, 2011
Messages
3
Programming Experience
1-3
I am experiencing aproblem in my VB.NET App. The salary form is a databound form in my app to a linq data source. There are several text boxes to enter and calculate different salary fields. e.g. Basic Salary, Budgetary Allowance and Adjusted Basic Salary...

all the above three controls are bound to the datasource. now on the Leave events of the Basic Salary and Budgetary Allowance there is a function to calculate Adjusted basic salary.

The problem is i dont see the calculated amount in the adjusted basic salary but i see only the underlying data in the database instead of the programmatically calculated amount.

i suspect this could be because of the databound field. are there any alternative solutions? Thanks
 
Absolutely!. The following code is the event to assign the calculated value to txtAdjustedBasic textbox. All of the below textboxes are databound to a linq datasource in design view.

My problem is when I enter a value in either of the txtBasicSalary or txtBudgetaryAllowance textboxes for the first time, the txtAdjustedBasic does not display the calculated amount. but when i enter a value in the second time then the calculation made properly.

VB.NET:
    Dim dbPSNet As New PayrollDataContext

    Private Sub txtBasicSalary_Leave(ByVal sender As Object, ByVal e As System.EventArgs) _
                                    Handles txtBasicSalary.Leave, txtBudgetaryAllowance.Leave
        Dim dBasicSalary As Decimal = txtBasicSalary.Text
        Dim dBudgetaryAllowance As Decimal = txtBudgetaryAllowance.Text
        txtAdjustedBasic.Text = dBasicSalary + dBudgetaryAllowance
    End Sub
 
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        TblSalaryBindingSource.DataSource = dbPSNet.tblSalaries
    End Sub
 
When working with bound data in code, you should always work with the data source and not the UI. You should get the bound item from the BindingSource, cast it as the appropriate type and then operate on it. The UI will update automatically thanks to the binding.

Also, would it be possible for the user to navigate to a different record without a Leave event being raised? I think so if you're using a BindingNavigator. Not so if you're using your own Buttons. Do your bound items raise a PropertyChanged event? If so then it would be a better option to handle that than the Leave events of the controls.

Finally, I hope the TextBox bound to the calculated value is read-only because you obviously don't want the user editing it.
 
Thank you for your reply and you are correct. when assignining the calculated value to the textbox it assigns at the code level. but bindingsource rest it to the underlying database value.

i must use the binding context at code level. Thanks for the help.
 
Back
Top