I have the following button click event:
private void button_GetTrucks_Click(object sender, EventArgs e)
{
if (textBox_CompanyCode.Text.Length != 3)
{
_errorProvider.SetError(button_GetTrucks, "Invalid company code.");
return;
}
textBox_CompanyCode.Enabled = false;
button_GetTrucks.Enabled = false;
_corporationId = GetCorporationId(textBox_CompanyCode.Text);
if(_corporationId == Guid.Empty)
{
_errorProvider.SetError(button_GetTrucks, "Could not find company.");
return;
}
dataGridView1.DataSource = null;
_soureItemCollection = null;
textBox_CorporationId.Text = _corporationId.ToString();
var query = GetTrucks(_corporationId);
_soureItemCollection = new ObservableCollection<Truck>(query);
dataGridView1.DataSource = _soureItemCollection;
MakeDataGridViewPerty();
button_GetTrucks.Enabled = true;
textBox_CompanyCode.Enabled = true;
}
public static List<Truck> GetTrucks(Guid corporationId)
{
return (from trk in Entity.Trucks
where trk.CorporationId == corporationId
orderby trk.TruckNumber
select trk).ToList();
}
When I get the data initially by clicking the button, it works fine. If the data has changed, due to another program changing the data and I click this button again to refresh the data, it stays the same and does not display the changed data.
If I restart the application, click the button, the new data is displayed correctly.
So, it takes me restarting the application to reload the data.
Why is the button click not reloading the data?
I have seen where you have to add in a databind to get it to rebind
dataGridView1.DataSource = _soureItemCollection;
dataGridView1.Databind();
Before this call: var query = GetTrucks(_corporationId); place this one first:
Entity.Refresh(RefreshMode.OverwriteCurrentValues,Entity.Trucks);
Related
I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)
Hi I have one gridview on the left and I have Multiview pane on the right. Basically what I am trying to do is when the use click select in the gridview, the information of that row will display in the Multiview.
I have two view.
View 1 contains label saying please select row to view full details.
View 2 basically retrieving all the necessary data.
The problem is, in my view 2, I do allow user to update the data. When the user updates the data and save, the view will go back to its initial view. And when the user click on the same row, it will then display the updated information.
How can I do such that when they save the changes, the view will show the updated information?
I have tried putting updatepanel but it does not work too.
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
xxBLL schBLL = new xxBLL ();
GVFBAcc.DataSource = schBLL.getInfo();
GVFBAcc.DataBind();
MainView.ActiveViewIndex = 1;
}
protected void GVFBAcc_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string Selectedid = GVFBAcc.SelectedRow.Cells[1].Text;//get user id
int selectedIdtoPass = Convert.ToInt32(Selectedid);
xxBLL getRecord = new xxBLL ();
addInfo InfoRetrieve = new addInfo ();
InfoRetrieve = getRecord.getDetail(selectedIdtoPass);
lbid.Text = Convert.ToString(InfoRetrieve .info_id1);
lbType.Text = InfoRetrieve .type;
lbName.Text = InfoRetrieve .name;
lbAbb.Text = InfoRetrieve .abb;
MainView.ActiveViewIndex = 0;
}
catch (Exception ex)
{
lbMessage.Visible = true;
lbMessage.Text = "Please select a Row.";
}
}
protected void editInfo_Click(object sender, ImageClickEventArgs e)
{
MainView.ActiveViewIndex = 0;
string cIcon = editInfo.ImageUrl;
if (cIcon.Equals("~/images/edit.png"))
{
editInfo.ImageUrl = "~/images/save.png";
lblEdit.Text = "";
tbName.Text = lbName.Text;
tbAbb.Text = lbAbb.Text;
tbtype.Text = lbType.Text;
lbName.Visible = false;
lbAbb.Visible = false;
lbType.Visible = true;
tbName.Visible = true;
tbAbb.Visible = true;
tbtype.Visible = false;
}
else if (cIcon.Equals("~/images/save.png"))
{
addInfo[] update = new addInfo[1];
int id = Convert.ToInt32(lbid.Text);
string name = tbName.Text;
string abb = tbAbb.Text;
addInfo updated = new addInfo(name, id, abb);
update[0] = updated;
xxBLL obj = new xxBLL ();
if (obj.updateDetail(update))
{
editInfo.ImageUrl = "~/images/edit.png";
lbName.Visible = true;
lbAbb.Visible = true;
lbType.Visible = true;
tbName.Visible = false;
tbAbb.Visible = false;
tbtype.Visible = false;
lblEdit.Text = "Saved";
lblEdit.ForeColor = Color.Green;
tbName.Text = lbName.Text;
tbAbb.Text = lbAbb.Text;
tbtype.Text = lbType.Text;
}
}
}
When the user updates the data and save, the view will go back to its initial view. And when the user click on the same row, it will then display the updated information. How can I do such that when they save the changes, the view will show the updated information?
or alternative How do i call the button click event at page load so that when the user clicks the save button, it will display the updated infomation
In my Windows application I had a job code combobox and when user selects a jobcode from the combobox it will get the corresponding data from database and will display it in a datagridview below the combobox. All is fine and I am able to load data corresponding to selected jobcode.
I used the this code
public void loadcompljobcodecombobox()
{
completedcobcodeadapterTableAdapter cmpltjbcd = new completedcobcodeadapterTableAdapter();
cmpltjbcd.Connection = new OleDbConnection(Program.ConnStr);
DataTable dt= cmpltjbcd.GetData(int.Parse(cmbcutcode.SelectedValue.ToString()));
if (dt.Rows.Count > 0)
{
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
txtcompanyname.Text = "companyname";
cmbjobcode.DataSource = dt;
}
else
{
MessageBox.Show("NO JobCode to be invoiced");
}
}
private void cmbjobcode_SelectedValueChanged(object sender, EventArgs e)
{
tbltoinvoicedtableTableAdapter tbltoinvce = new tbltoinvoicedtableTableAdapter();
tbltoinvce.Connection = new OleDbConnection(Program.ConnStr);
if (cmbjobcode.SelectedValue != null)
{
DataTable dt = tbltoinvce.GetDataBy(int.Parse(cmbjobcode.SelectedValue.ToString()));
dataGridView1.DataSource = dt;
}
}
Now my requirement is user must be able to select more than one jobcode details at a time for invoicing i.e. if he selects one value from jobcode corresponding data should be added in datagridview and when he select another jobcode its corresponding data should be added as next row in the Datagridview.
I had tried very much and find no way can anyone suggest an idea or example
If I understand you correctly, I would try something like this. This isn't tested but it's an idea.
At Form Level:
private BindingList<DataRow> jobList;
Then to add to your current code...
private void cmbjobcode_SelectedValueChanged(object sender, EventArgs e)
{
tbltoinvoicedtableTableAdapter tbltoinvce = new tbltoinvoicedtableTableAdapter();
tbltoinvce.Connection = new OleDbConnection(Program.ConnStr);
if (cmbjobcode.SelectedValue != null)
{
DataRow job = tbltoinvce.GetDataBy(int.Parse(cmbjobcode.SelectedValue.ToString())).Rows[0];
if (jobList == null)
{
jobList = new BindingList<DataRow>();
jobList.Add(job);
dataGridView1.DataSource = jobList;
}
else
{
if (!jobList.Contains(job));
jobList.Add(job);
}
}
}
**Edit: This is assuming your job data contains only one row of data since your question asked for how to add "a row".
I realy need help for this. I am using AjaxControlToolkit.TabContainer and using ASP.NET Framework 4.0. Gridview,textbox and button are placed in TabContainer on asp page. When I press button postback does happen but its not binding gridview to datatable and textbox contents are also not updated.
I debug the code and found when i press button postback does happen and content does fill up in gridview and textbox value also assigned with new value. but values doesnt display on the page. I dont know why its happening. please help.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ListBoxCustomer.Items.Count != 0)
{
int[] _selectedItems = ListBoxCustomer.GetSelectedIndices();
string _comma = "";
string _custID = "";
InitializeConnection();
if (_selectedItems.Length != 0)
{
foreach (int i in _selectedItems)
{
_custID = _custID + _comma + ListBoxCustomer.Items[i].Value;
_comma = ",";
}
if (custObj != null)
{
//DataTable _dt = new DataTable();
DataSet _ds = new DataSet();
GridViewCustomer.Visible = true;
GridViewCustomer.AutoGenerateColumns = true;
_ds = custObj.GetSelectedCustomers(1, _custID);
GridViewCustomer.DataSource = _ds.Tables[0];
GridViewCustomer.DataBind();
TextBoxTest.Text = GridViewCustomer.Rows.Count.ToString();
TextBoxTest.Text = "test";
}
}
}
}
}
thanks.
Perhaps the DataBind code is never being reached. Have you set some breakpoints to make sure the if-statements aren't blocking you? That is... Is ListBoxCustomer.Items.Count definitely not zero... Is custObj definitely not null?
Where do you assign a value to custObj?
I have a DataGridView in a form and I want to programmatically click its first row. I have found code to select its rows or columns from code.
For eg.
datagridview.Columns[0].Selected = true;
datagridview.Rows[0].Selected = true;
However this code is not raising the click event on the datagridview. If any one has coded how to click a datagridview from code, please extend your kind help.
Simply call the event handler method e.g.:
datagridviewRowClickedEventHandler(new object(), new eventargs());
If you use the sender or e parameters in the event handler then you will need to work out how to pass in the correct values.
Insert the follwing code into your project where appropriate (Usually on the form which has the datagridview).
Make sure to change the name of the DataGridView from dataGridView1 to the appropriate one on your form.
private void Form1_Load(object sender, EventArgs e)
{
//call the cell click event with the first cell as the parameters.
dataGridView1_CellClick(dataGridView1, new DataGridViewCellEventArgs(0, 0));
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//put your code for handling cell click here
}
It looks like you have the first half, setting the propers rows Selected value to true. Now you can programatically call the row click handler and it should proceed as if you had clicked it within the GUI.
datagridview.Columns[0].Selected = true;
datagridview.Rows[0].Selected = true;
It makes look the row like selected but it won't change dataGridView.CurrentRow. So it could be an issue.
dataGridView.CurrentCell = dataGridView[<column>, <row>];
will change CurrentRow value too.
Hope it will help.
I assume you want to apply DataSource and select the first row? Right?
The best way to do it like this
private async void DgvAreas_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
}
And here is the code to simulate click on row.
DgvAreas_RowStateChanged(dgvAreas, new DataGridViewRowStateChangedEventArgs(dgvAreas.Rows[0], DataGridViewElementStates.Selected));
In my case I have 3 DataGridViews so I populate the first one easly.
The second one I populate when user click the first DataGridView and in this case I use DgvStaff_RowStateChanged event.
And in this event DgvStaff_RowStateChanged I have the code to get data async and populate the third DataGridView and after I apply data source for the second DataGridView I need to get data for the first row of this view and display it in the third DataGridView. It is cascade logic.
private async void DgvStaff_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
try
{
// For any other operation except, StateChanged, do nothing
if (e.StateChanged != DataGridViewElementStates.Selected) return;
if (sender is MetroFramework.Controls.MetroGrid)
{
if ((sender as MetroFramework.Controls.MetroGrid).SelectedRows.Count > 0)
{
dgvGeoData.DataSource = null;
dgvAreas.DataSource = null;
metroProgressSpinnerMain.Visible = true;
panelFilter.Enabled = false;
dgvAreas.RowStateChanged -= DgvAreas_RowStateChanged;
var selectedRow = (sender as MetroFramework.Controls.MetroGrid).SelectedRows[0];
var machineModelShortView = (MachineModelShortView)selectedRow.DataBoundItem;
var startTime = Convert.ToDateTime(dateTimePickerStart.Value.ToShortDateString());
var endTime = Convert.ToDateTime(metroDateTimeEnd.Value.ToShortDateString());
var areas = await UpdateAreaItems(machineModelShortView.MachineID, startTime, endTime);
if (areas.Any())
{
BeginInvoke((Action)(() =>
{
dgvAreas.DataSource = areas.OrderBy(x => x.AreaID).ThenBy(x => x.TimeStart).ToList();
dgvAreas.RowStateChanged += DgvAreas_RowStateChanged;
// !!! This is how you simulate click to the FIRST ROW dgvAreas.Rows[0]
DgvAreas_RowStateChanged(dgvAreas,
new DataGridViewRowStateChangedEventArgs(dgvAreas.Rows[0], DataGridViewElementStates.Selected));
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
else
{
BeginInvoke((Action)(() =>
{
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
And here
private async void DgvAreas_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
try
{
// For any other operation except, StateChanged, do nothing
if (e.StateChanged != DataGridViewElementStates.Selected) return;
//Get GeoData
if (sender is MetroFramework.Controls.MetroGrid)
{
if ((sender as MetroFramework.Controls.MetroGrid).SelectedRows.Count > 0)
{
dgvGeoData.DataSource = null;
metroProgressSpinnerMain.Visible = true;
panelFilter.Enabled = false;
var selectedRow = (sender as MetroFramework.Controls.MetroGrid).SelectedRows[0];
var areaItem = (AreaItem)selectedRow.DataBoundItem;
var geoData = await UpdateWDataPositionItems(areaItem.MachineID, areaItem.TimeStart, areaItem.TimeEnd.Value);
if (geoData.Any())
{
BeginInvoke((Action)(() =>
{
dgvGeoData.DataSource = geoData.OrderBy(x => x.AtTime).ToList();
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
else
{
BeginInvoke((Action)(() =>
{
metroProgressSpinnerMain.Visible = false;
panelFilter.Enabled = true;
}));
}
}
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}