How do I select last edited row using a button - c#

I have a project to register customers using a DataGridView and It has 3 buttons:
"add" adds the values from the textbox
"delete" deletes the selected value in the DataGridView
"new" generates the next id number (they're consecutives) and clears all the textboxes fields
I think of adding a button named "cancel" to revert changes generated by the button "new" and it has to select the last edited row and show its cells values in the textbox.
I made a "cancel" button to select the last row in the list, but the last row in the list is not always the last edited
I'm using Windows Forms, not using a database.
private void bttn_cust_cancel_Click(object sender, EventArgs e)
{
if (dgv_customer.Rows.Count > 0)
{
dgv_customer.Rows[dgv_customer.Rows.Count - 2].Selected = true;
int i;
i = dgv_customer.SelectedCells[0].RowIndex;
txt_cust_clave.Text = dgv_customer.Rows[i].Cells[1].Value.ToString();
txt_cust_name.Text = dgv_customer.Rows[i].Cells[2].Value.ToString();
txt_cust_country.Text = dgv_customer.Rows[i].Cells[3].Value.ToString();
}
int currentType = Convert.ToInt32(txt_cust_id.Text);
txt_cust_id.Text = Convert.ToString(--currentType);
}

You could create a variable or class to hold the index and/or data of the last edited row. This class would be reinitialized every time the "New" button is pressed.

Related

implementing next and previous buttons(LinkedList)

I have some LinkedList. I filled it with some DataTable from DataSet. So question is how do I implement button "Next" and "Previous" on Windows Form to navigate my tables?
LinkedListNode<DataTable> lln = new
LinkedListNode<DataTable(ds.Tables("GRAPHICS"))
LinkedList<DataTable> ll = new LinkedList<DataTable>
LinkedListClass.ll.AddFirst(lln)
LinkedListClass.ll.AddLast(ds.Tables("COORDS"))
LinkedListClass.ll.AddLast(ds.Tables("METHODS"))
I expect to press button "Next" get table "COORDS" and press "Previous" button get previous value ( "GRAPHICS" table)
First you'll have to store a current position. So add i.e. a property that stores the current item's table name. Than add two "click" events for your buttons(previous and next) and handle these events. Something like this
private string _currentTableName; // or reference list item directly
// use this pseudo code to create "Previous" method as well
void NextButtonPressed(object sender, EventArgs e)
{
// Get current element using stored name
if(string.IsNullOrEmpty(_currentTableName))
{
_currentTableName = firstElement.Name;
// show first
Display(firstElement);
}
else
{
// get current element
// get next element
_currentTableName = nextElement.Name;
Display(nextElement);
}
}

How to get a ComboBox in a DataGridViewCell to drop down after a single click?

I have a DataGridView which has it's first column's style set to a ComboBox rather than the default TextBox. Since the number of rows in the DataGridView is not fixed on startup I cannot load in data to the ComboBoxes for each row when a new row is added. So I tried loading on the event of a user adding a row to the DataGridView:
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
// Identifiers used are:
var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
var myDataTable = myTableAdapter.GetData();
int rowIndex = myDataGridView.CurrentcellAddress.Y;
var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
string itemToAdd;
// Load in the data from the data table
foreach (System.Data.DataRow row in myDataTable.Rows)
{
// Get the current item to be added
itemToAdd = row[0].ToString();
// Make sure there are no duplicates
if (!comboBoxCell.Items.Contains(itemToAdd))
{
comboBoxCell.Items.Add(itemToAdd)
}
}
}
but this only will allow the user to see the drop down options after a second click. I would like to be able to have the user only click on the combo box once and see the options rather than the less intuitive double click. How can this be done?
The cell must gain focus for the drop down to occur, so the double click is actually a single click to gain focus on that cell and the second click is what causes the drop down to occur. So to see how to change focus following this link. I was able to modify the code with a single line of code
public void myDataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
// Identifiers used are:
var myTableAdapter = new databaseTableAdapters.myTableTableAdapter();
var myDataTable = myTableAdapter.GetData();
int rowIndex = myDataGridView.CurrentcellAddress.Y;
var comboBoxCell = (DataGridViewComboBoxCell)myDataGridView.Rows[rowIndex].Cells[0];
string itemToAdd;
// Load in the data from the data table
foreach (System.Data.DataRow row in myDataTable.Rows)
{
// Get the current item to be added
itemToAdd = row[0].ToString();
// Make sure there are no duplicates
if (!comboBoxCell.Items.Contains(itemToAdd))
{
comboBoxCell.Items.Add(itemToAdd)
}
}
// Send the focus to the next combo box (removes need for a double click)
myDataGridView.CurrentCell = myDataGridView.Rows[rowIndex + 1].Cells[0]; // <--- HERE
}

Error on passing data back to Dropdownlist asp .net webform

I have a dropdownlist that cannot be used for editing purpose. When button Edit is clicked inside listview where data exists, data is supposed to pass back to dropdownlist and other textboxes where the form is located outside listview. Passing data back to textboxes is ok. The problem is dropdownlist data that I want to edit was added to dropdownlist as another record. Please take a loot at picture, and I have to reselect the correct one. Otherwise, that selected data (e.g. December in picture) has no datavaluefield and it stops running if I didn't choose bottom December and click Update button. Here is my code for dropdownlist for months. Any help is appreciated for this. Thank you.
public void BindMonth()
{
ddlStartMonth.DataSource = objUIHelpers.GetAllMonths();
ddlStartMonth.DataTextField = "StartMonthName";
ddlStartMonth.DataValueField = "MonthId";
ddlStartMonth.DataBind();
ddlStartMonth.Items.Insert(0, "Select Start Month");}
Then, I put this method in page load like this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindMonth();
}
}
This is listview data item editing
protected void lvEducation_ItemCommand(object sender, ListViewCommandEventArgs e)
{
switch (e.CommandName)
{
//Delete Method will be fired when command name "Delete" inside Listview is clicked.
case ("Delete"):
int EducationId = Convert.ToInt32(e.CommandArgument);//pass Id of Experience to identify datarow to delete
// DeleteEducationById(ExperienceId);//Call bind to delete method and pass ExperienceId as argument
break;
//Edit Method will fired when command name "Edit" inside Listview is clicked.
case ("Edit"):
EducationId = Convert.ToInt32(e.CommandArgument); //pass Id of Experience to identify datarow to edit
BindEducationDataToEdit(EducationId);//Call bind to edit method and pass ExperienceId as argument
break;
}}
This is part of method that triggers to pass back data to edit.
public void BindEducationDataToEdit(int EducationId)
{
Education edu = objJFUserBAL.GetEducationByIdToEdit(EducationId);
txtAdditionalInfo.Text = edu.AdditionalInfo.ToString();
ddlEndMonth.SelectedItem.Text = edu.mo.EndMonthName;
}
When selected data is posted back for editing, I have extra data like this.
You should not be updating the SelectedItem.Text. This is changing the displayed text. Instead you should be updating which item is selected.
If you do not have access to the value of the month name, you can do the following:
ddlEndMonth.Items.FindByText(edu.mo.EndMonthName).Selected = true;
which will select the item with the month text assuming one exists.
If it is possible to have an edu.mo.EndMonthName which does not exist in the list of items, you will want to do some checks for null and treat accordingly.
You have to fill a list manually, because auto binding is not going to let you put a "select your month" item unless you have one in your data base :
public void BindMonth()
{
List<Month> listOfMonth = new List<Month>();
Month fakeMonth = new Month();
// you need to see your own
//code and try to make a fake month with these parameters you want
fakeMonth.StartMonthName = "Select Start Month";
fakeMonth.MonthId = 0;
listOfmounth.Add(fakeMonth);
foreach(Month m in objUIHelpers.GetAllMonths())
{
listOfMonth.Add(m)
}
ddlStartMonth.DataSource = listOfMonth;
ddlStartMonth.DataTextField = "StartMonthName";
ddlStartMonth.DataValueField = "MonthId";
ddlStartMonth.DataBind();
ddlStartMonth.Items.Insert(0, "Select Start Month");}
}

Set Focus on row by cell value

I have two grid views namely PositionsReadyListGridView and PositionsNotReadyListGridView.
Now the functionality requirement is on click of Button Set Not Ready the selected item from PositionsReadyListGridView is removed from this list and added to PositionsNotReadyListGridView.
Similarly on click of Button Set Ready the selected item from PositionsNotReadyListGridView is removed from this list and added to PositionsReadyListGridView.
I have implemented this functionality but I am unable to set Focus on the latest row which is added to the either of the GridView.
Is there a way that I can set Focus to the row according to cell
values?
For example in both of the Grids I have a column colID which is unique to a row.
Can I somehow use this ID to set Focus to the row added to either PositionsReadyListGridView (on Set Ready click) or PositionsNotReadyListGridView (on Set Not Ready Click)?
Thanks
You can use LocateByValue method, which returns RowHandle of located row and set this value to FocusedRowHandle property:
int rowHandle = PositionsReadyListGridView.LocateByValue("colID", ID);
if (rowHandle != GridControl.InvalidRowHandle)
PositionsReadyListGridView.FocusedRowHandle = rowHandle
to get the lately added row get it by
PositionsReadyListGridView.Rows.Count - 1
and for setting the focus
PositionsReadyListGridView.Rows[PositionsReadyListGridView.Rows.Count - 1].Cells[colID].Selected = true;
private void PositionsNotReadyListGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
this.PositionsNotReadyListGridView.Rows[e.RowIndex].Selected = true;
}
for devExpress use this code :
gridView1.FocusedRowHandle = gridView1.LocateByValue("columnName",value of columnName, null);

DataGridView selecting a specific row and retrieving all column values to an object array

I want to perform operation that On a button click event , Grid Currentrow entire data is passed to an object array
I have tried to search through following links :
DataGridView selecting a specific row and retrieving its values
Getting data from selected datagridview row and which event?
But they are talking about particular cell value
i tried to perform with code
DataRowView currentDataRowView = (DataRowView)grdGLSearch.CurrentRow.DataBoundItem;
DataRow row1 = currentDataRowView.Row;
But currentDataRowView is retrieving null
one of My Senior succesfully created a generic property GetSelectedRow()
it works like this :
var object =grdGLSearch.GetSelectedRow<T>();
and it has definition
public T GetSelectedRow<T>()
{
if (this.CurrentRowIndex == -1)
{
return default(T);
}
return (base.DataSource as BindingList<T>)[this.CurrentRowIndex];
}
But it is binded to only one Main grid , i also want to use this property to another Grids
I dont want data of a particular column , i want entire row data .. and dont want any iteration to be perform ...
Is there any single liner operation for this ?
Please suggest if I am missing any links
Since you are only showing 2 lines of code, I am really not sure exactly what is going on. First off, I get you want the entire row when you click some button. However, you never state how the current row is being selected.
In order to get the full selected row, you must have a selected cell. The MSDN documentation says this on the page for DataGridView.SelectedRow. So I am assuming that the user will click a cell, and you want the entire row. I would create a variable that will hold your selected row. Then when the user clicks the cell, automatically select the row and save it. Then when the button is clicked, just retrieve the the already saved row.
private DataGridViewRow selectedRow { get; set; }
Then have the event for when the user clicks a cell
private void grdGLSearch_CellClick(object sender, DataGridViewCellEventArgs e)
{
selectedRow = grdGLSearch.Rows[e.RowIndex];
}
Finally, the button click event
private void SubmitBtn_ItemClick(object sender, ItemClickEventArgs e)
{
// to target the specific data
var cellVal1 = selectedRow.Cells["SpecificCell1"].Value;
var cellVal2 = selectedRow.Cells["SpecificCell2"].Value;
}

Categories