Bindingsource won't update after the textbox Conrol updates - c#

I have a form which its controls are binded to a bindingsrource named "userbindingsource". When the form loads all the value in bindingsrource will be set to equivalent Textbox. But when the textboxes values change , the bindingsrource won't update. and still it shows the very first value
For example after load I change the first name in textbox and then click save Button to call the saveRecord(). when I check (userBindingSource.DataSource as User) , it still contains the first firstname without any changes.
public void SaveRecord()
{
int i = 0;
User user = userBindingSource.DataSource as User;
if (user.Id > 0)
user.State = State.Modified;
using (ECarServiceClient client = new ECarServiceClient())
{
i = client.SaveUser(user);
}
}
how can make the bindingsource updates automatically?

If the textbox binding has DataSourceUpdateMode.OnValidation (the default) and you go right from typing in a textbox to clicking the Save button, the Save click is handled before the textbox validates. Validation is what makes the BindingSource update the User object.
The fix would be to call this.Validate() at the beginning of SaveRecord. This triggers validation of the focused control within the current form and all its ancestors.

Related

Change Value of a Dynamically Created Text Box when button is clicked C#

I have dynamically created a button using a function I made which is meant to increase the value of another button created using a similar function. I'm able to retrieve the name of the dynamically created textbox, but since it is dynamically created, I can't reference it.
I've tried to pass the textbox through as a parameter, but it doesn't appear that I'm able to pass extra parameters:
Button ButtonDecreaseValue= addButton(ItemName, "-");
TextBox TextBoxItemAmount = addTextBox(ItemName, "0");
So, how would I change the value of textbox one when ButtonRemoveItem is clicked?
I've created an event handler for the button, like so:
ButtonIncreaseValue.Click += new EventHandler(ItemDecreased);
But, inside the event handler, I'm unsure how I would change the textbox name.
private void ItemDecreased(object sender, EventArgs e)
{
Button currentItem = (Button)sender;
int ItemNo = Convert.ToInt32(currentItem.Tag);
DataRow ItemInfo = getItemDetails(ItemNo);
ItemInfo[0].ToString();
}
When clicking the button, the corresponding textbox should decrease in value.
Assuming this is Windows Forms
You said you have the name of the TextBox? You should be able to find it with that.
private void ItemDecreased(object sender, EventArgs e)
{
string textBoxName = HoweverYouGetTheDynamicTextBoxName();
// Assumptions:
// 1. ItemDecreased is a method on a Form or a UserControl.
// 2. There is only one TextBox with the given name in the Form or UserControl.
// 3. The TextBox is added to the Form or UserControl's Controls property.
TextBox tb = Controls.Find(textBoxName, true).OfType<TextBox>().SingleOrDefault();
if (tb is null)
{
// Couldn't find the text box for some reason.
}
// tb references the dynamically created text box.
}

Remember checked checkboxes in DataGridView

I have a DataGridView where the first column is a DataGridViewCheckBoxColumn. The user checks some checkboxes to indicate which items are to be deleted.
When I hide the form and reload it, I need the DataGridView to remember which checkboxes were checked.
You need to save the changes at least at the point where you close your Form (if you just hide it, why reload then?).
The way I usually work this out is listening to the Dgv's CellEndEdit event:
SomeDataGridView.CellEndEdit += ObjectPropertyChanged
then in the Callback you can get the Object back by using the "DataBoundItem" prop of the Dgv and process / save it however you need:
protected virtual void ObjectPropertyChanged(object sender, DataGridViewVellEventArgs e)
{
var selectedObject = ((DataGridView)sender).Rows[e.RowIndex].DataBoundItem;
//Assuming you stored in a List and each Object has an ID as prop:
var indx = _Objects.IndexOf(_Objects.Where(o => o.ID.Equals(selectedObject.ID)))
_Objects.Remove(indx)
_Objects.Insert(indx, selectedObject)
}
You could also do database update, write to a text-file, save in configuration, ...

Displaying data from a DataGridView on one Form into TextBoxes on another

I have two forms. ShoppingBasketForm.cs and EditBasketPopup.cs.
ShoppingBasketForm.cs displays a shopping basket in a DataGridView called dataGridBasket which is bound to a seperate List<OrderItem>OrderItems which comes from my OrderItemclass. This can be added to by filling in the provided text boxes/numericUpDowns on the page Product Name Quantity and LatestPrice and then clicking the Add button btnAdd. It also has the ability to remove data from the selected row by clicking the Remove button btnRemove.
I'm now trying to implement an Edit button btnEdit where once clicked, it instantiates the EditBasketPopup form. On this form there are the three text boxes/ numeric up downs displayed again ProductName Quantity and LatestPrice.
How do I take the data from the selected row on the dataGridBasket (User cannot select single cells) and use that to fill the three text boxes when the user activates the btnEdit click event?
I tried creating a properties inside the EditBasketPopup.cs to hold the data from the first form, but was unsure how to extract the data from the selected row in the dataGridBasket in string form and also came across the problem of needing the individual data from each cell in the row, seeing as they are bound to different properties.
I obviously don't have much example code for this question as it's a theory as to how rather than why but if you need anything just let me know.
#Harry Sweetman ok first to get the selected element of your datagridview you can make something like this:
//recover the view row
DataGridViewRow drv = (DataGridViewRow)dataGridBasket.Current;
//if the row is not empty => basket was selected in the dataGridView
if (drv.Cells[0].Value != null)
{
//Here we get the first cell selected let say the name is like the id:
string idBasketToEdit = drv.Cells[0].Value.ToString().Clone().ToString();
//Now we instantiate the form EditBasketPopoup, but sending the selected basket as a parameter
frmEdit = new EditBasketPopoup(idBasketToEdit);
frmEdicion.Name = "Edit basket";
frmEdicion.ShowDialog();
}
Also you need to have a form constructor in EditBasketPopup.cs with a Basket parameter like this:
public EditBasketPopup(string idBasket)
{
InitializeComponent();
Basket b = control.GetBasket(idBasket);
//You set the form boxes:
txtProductName.Text = b.ProductName;
txtLatestPrice.Text = b.LatestPrice;
txtQuantity.Text = b.Quantity;
}
Finally let s suppose you have a controller (Ex. BasketController) were you have some logic. Here it 's supposed that you search the Basket you want to edit on the collection that it 's binding your datagridview (dataGridBasket).
public Basket GetBasket(string idBasket)
{
try
{
//basketCollection is the one that you use to bind dataGridBasket
return basketCollection.Find(x => x.idBasket.Equals(idBasket));
}
catch (Exception ex)
{
throw ex;
}
}

Usercontrol that dynamically generates a list of controls on postback

I want to create a reusable user control that allows the user to create and remove tags.
It should have a textbox where the user can enter a tag name, and a button to submit the tag.
After sumbitting the tag, it should dynamically create a label with the tag name with a "X" button to remove it for every entered tag.
Something like this:
[ Textbox ] [Submit]
[X] Tag 1
[X] Tag 2
[X] Tag 3
The issue is that I cannot figure out how to make everything work properly.
Selector.ascx
< markup for the textbox >
< markup for the sumbit button >
<asp:Placeholder runat="server" ID="PHList" />
I'm using an asp:Placeholder to generate the dynamic controls.
Selector.ascx.cs
I need to keep track of the generated controls between postbacks.
I'm using a List<string> stored in the viewstate:
private List<string> SelectedTags
{
get
{
return (List<string>) ViewState["SelectedTags"];
}
set { ViewState["SelectedTags"] = value; }
}
When I click the submit button, I add a new tag to the SelectedTags list, and call the RefreshPlaceholder function:
void RefreshPlaceholder()
{
PHList.Controls.Clear();
foreach(var x in SelectedTags)
{
// generate a label and the "X" button, wiring it with a lambda
}
}
When I click the submit button, a new (button, label) pair is correctly generated and displayed after postback.
When I click any of the generated "X" buttons, however, I get an error because the click event fired by the dynamically generated button cannot find the sender button anymore, since it hasn't been generated yet.
If I try to generate the buttons in OnLoad, the same issue occurs, as postback events occur before Page.Load.
If I try to generate the buttons in OnInit, the ViewState has not been updated yet, so the generated list will be outdated as the SelectedTags viewstate list is not yet updated.
I can't seem to find a solution to make everything work as intended. What am I doing wrong?
Declare a List of type Buttons on OnInit method; then in RefreshPlaceHolder retrieve and loop through selected tags and add them to the List
protected override void OnInit(EventArgs e)
{
List<Button> listButtons ;
base.OnInit(e);
}
void RefreshPlaceholder()
{
listButtons = new List<Button>();
PHList.Controls.Clear();
foreach(var x in SelectedTags)
{
Button b = new Button();
b.Text=x;
listButtons.add(b);
// generate a label and the "X" button, wiring it with a lambda
}
}

C# EF SaveChanges dosen't save last value

I have bindingList bound to TextBoxes. When I enter new value in textboxes and press save button the value from last Textbox dosen't save in database. But when I pressed Tab key before save button every values from texboxes were saved. How resolve this problem with unsaved last value?
....
BindingList<Zamo> myList;
pg = new PGEntities();
var query = (from zam in pg.Zamo where zam.ID == rekord.ID).Take(1);
myList = new BindingList<Zamo>(query.ToList());
zamoBindingSource.DataSource = myList;
....
private void SaveButton()
{
pg.SaveChanges();
}
This occurs only when I save by button in BindingNavigation.
When you press the tab key it is getting saved? that probably means the saveButton event is reading the text before the entered text is considered. Try to lose focus on the textbox, then save.

Categories

Resources