how to get next row data in gridview? - c#

i want to get next data in gridview, the thing is when i use break; it totally out of loop, but when i dont use break; it otomatically call the last row data of the text that i type.
private void button7_Click(object sender, EventArgs e)
{
for (int i = 0; i < gridView1.RowCount; i++)
{
var row = gridView1.GetDataRow(i);
var genre = row["genre"].ToString();
if (genre.IndexOf(textBox8.Text, StringComparison.OrdinalIgnoreCase) >= 0)
{
gridView1.FocusedRowHandle = i;
break;
}
}
}
if i dont use break it will select the last data with 'ba' = basketball.
what i want is when i click next it select ballet and stop, and when i click next button again it select basketball

use an int variable to store the current iteration of loop:
int iteration=0;
private void button7_Click(object sender, EventArgs e)
{
for (int i = iteration; i < gridView1.RowCount; i++)
{
var row = gridView1.GetDataRow(i);
var genre = row["genre"].ToString();
if (genre.IndexOf(textBox8.Text, StringComparison.OrdinalIgnoreCase) >= 0)
{
gridView1.FocusedRowHandle = i;
iteration=i+1;
break;
}
}
}
And on Find button you can reset iteration to 0

Related

Simulate CTRL down until I desire in c#?

I'm trying to simulate a user pressing ctrl down, the main goal would be in a datagridview when I select something programarly (initially) I dont want the user to then change that selection if not just add on to it or subtract, just as if you were to hold ctrl + left mouse click. I have no idea where to even begin. I tried to create a selection change event conbined with logicals but that will cause an infinite loop since we would be selecting one by a user then the code change other and other etc infinitely triggering that event. Please help, I'm sort of new to coding. I also don't know how to determine whether a ctrl key has been pressed, is pressed and being held.
private void selecttionh(object sender, EventArgs e)
{
if (stage == "4A" || stage == "3B" && ModifierKeys.HasFlag(Keys.Control))
{
int nothing = 0;
btnclickercl bt = new btnclickercl();
bt.dataGridView1_SelectionChanged(sender, e, dataGridViewReslist, dataGridViewnewres, nothing);
}
if (stage == "4A" || stage == "3B" && (ModifierKeys & Keys.Control) != Keys.Control)
{
MessageBox.Show("Please Press and hold " + "'ctrl'" + " to continue");
dataGridViewReslist.ClearSelection();
for (int i = 0; i < ResRoomSelections.Count; i++)
{
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
}
}
else
{
dataGridViewReslist.ClearSelection();
for (int i = 0; i < ResRoomSelections.Count; i++)
{
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
}
}
}
The way to make this happen is to store the selection state separately, update it when the user clicks a cell, then re-apply it. This prevents the selection from being lost every time they click. If you hook the proper event handlers (mouseup, not click) you can do this without the screen flickering and otherwise being a mess to look at.
Everything you need is in this class, including an extension method SetupToggledSelectionMode(), which is your entry point.
static public class Example
{
static private bool[][] GetSelectionState(DataGridView input)
{
int rowCount = input.Rows.Count;
int columnCount = input.Columns.Count;
var result = new bool[rowCount][];
for (var r = 0; r < rowCount; r++)
{
result[r] = new bool[columnCount];
for (var c = 0; c < columnCount; c++)
{
var cell = input.Rows[r].Cells[c];
result[r][c] = cell.Selected;
}
}
return result;
}
static private void SetSelectionState(DataGridView input, bool[][] selectionState)
{
for (int r = 0; r <= selectionState.GetUpperBound(0); r++)
{
for (int c = 0; c <= selectionState[r].GetUpperBound(0); c++)
{
input.Rows[r].Cells[c].Selected = selectionState[r][c];
}
}
}
static public void SetupToggledSelectionMode(this DataGridView input)
{
bool[][] selectionState = GetSelectionState(input); //This will be stored in a closure due to the lambda expressions below
input.CellMouseUp += (object sender, DataGridViewCellMouseEventArgs e) =>
{
selectionState[e.RowIndex][e.ColumnIndex] = !selectionState[e.RowIndex][e.ColumnIndex];
SetSelectionState(input, selectionState);
};
input.SelectionChanged += (object sender, EventArgs e) =>
{
if (selectionState != null)
{
SetSelectionState(input, selectionState);
}
};
}
}
To use, populate your gridview, set up the initial selection programmatically, and call it like this:
myDataGrid.DataSource = myData;
myDataGrid.Refresh();
myDataGrid.SelectAll();
myDataGrid.SetupToggledSelectionMode();
The SetupToggledSelectionMode() method will register the necessary event handlers and store the selection state of the grid in a closed variable accessible to both handlers. So you won't have to declare anything additional; just call the method.
Thank you for this, this really helped me. all I did was to make it more efficient.Since it would call the Selection change every step of the way, so I got rid of that event completely and only kept the CellMouseup Event.
static private bool[][] GetSelectionState(DataGridView input)
{
int rowCount = input.Rows.Count;
int columnCount = input.Columns.Count;
var result = new List<int[]>();
for (var r = 0; r < rowCount; r++)
{
for (var c = 0; c < columnCount; c++)
{
if(input.Rows[r].Cells[c].Selected==true)
{
result.add(new int[]{r,c});//will keep only the integer of selected items
}
}
}
return result;//this for me was a recycled variable it can be used or recycled from somewhere else
}
private void SetSelectionState(DataGridView input,result)
{
for (int i=0;i<result.Count;i++)
{
input.Rows[result[i][0]].Cells[result[i][1]].Selected = true;
}
}
public void SetupToggledSelectionMode(DataGridView input,result)
{
for (int i=0;i<result.Count;i++)
{
if(result[i].SequenceEqual(new int[] { e.RowIndex, e.ColumnIndex }))
{
result.RemoveAt(i);
continueer = 1;
break;
}
}
if (continueer == 0)
{
ResRoomSelections.Add(new int[] { e.RowIndex, e.ColumnIndex });
}
SetSelectionState(input);
//whatever else you need to do
}
I know there is still a better way to search List but I could not get a lamda search to work so I just used brute force
-Thank you John Wu for all

Remove TabPage from TabControl

So i need to dynamically add and delete some TabPage. User clicked "Show Tab" = storage_pageadded.
private void storage_menuItem_Click(object sender, EventArgs e) {
storage_page.Text = storage_page.Name = "Storage";
main_tabControl.TabPages.Add(storage_page);
main_tabControl.SelectedTab = storage_page;
}
And the when he chooses another page the storage_page has to be removed
private void main_tabControl_SelectedIndexChanged(object sender, EventArgs e) {
for (int i = 0; i < main_tabControl.TabPages.Count; i++) {
if (main_tabControl.TabPages[i].Name.Equals("storage", StringComparison.OrdinalIgnoreCase) && main_tabControl.SelectedTab.Name != "Storage") {
main_tabControl.TabPages.RemoveAt(i);
break;
}
}
}
When i click "Show Tab" page shows up. But when i select other page i see the ArgumentOutOfRangeException leading to Application.Run(new Form_Authentication()); line
How can i do that?
I think the problem is you increase i variable by 1 from 0 to main_tabControl.TabPages.Count
I assume that main_tabControl.TabPages.Count = 10, what is happended if you're removing 7th element? At that time, main_tabControl.TabPages.Count = 4 and i variable = 6. So, i variable is exceed the range of TabPages.
You should to change your code:
private void main_tabControl_SelectedIndexChanged(object sender, EventArgs e) {
for (int i = main_tabControl.TabPages.Count - 1; i >=0 ; i--) {
if (main_tabControl.TabPages[i].Name.Equals("storage", StringComparison.OrdinalIgnoreCase) && main_tabControl.SelectedTab.Name != "Storage") {
main_tabControl.TabPages[i].Dispose();
break;
}
}
}

Fill Data in Listbox with another Listbox which is having Data-Bound

I have this two list-box In that first list-box is fill on Combo-box Selected index changed, so List-box 1 is Bounded. Now when I press the > button all selected item in List-box 1 is display in List-box 2.
But instead of Names, I get System.Data.DataRowView
so my question is I want Names instead of this System.Data.DataRowView
my code is this
private void btnSelect1ItemFrom_Click(object sender, EventArgs e)
{
if (listBoxSelectToLedger.Items.Count > 0)
{
for (int i = 0; listBoxSelectToLedger.Items.Count > i; )
{
listBoxSelectToLedger.Items.Remove(listBoxSelectToLedger.Items[i].ToString());
}
}
if (listBoxSelectFromLedger.SelectedItem != null)
{
** for (int i = 0; i < listBoxSelectFromLedger.SelectedItems.Count; i++)
{
listBoxSelectToLedger.Items.Add(listBoxSelectFromLedger.SelectedItems[i].ToString());
} **
}
else
{
MessageBox.Show("No item Selected");
}
* I think I am some where Wrong in Second IF Condition in my Code *
Plz Help me
Thanks in Advance
Try this...
private void button1_Click(object sender, EventArgs e)
{
if(listBoxFrom.SelectedItems.Count>0)
{
for (int x = listBoxFrom.SelectedIndices.Count - 1; x >= 0; x--)
{
int idx = listBoxFrom.SelectedIndices[x];
listBoxTo.Items.Add(listBoxFrom.Items[idx]);
listBoxFrom.Items.RemoveAt(idx);
}
}
}
Hiii.. Deep, use the below code to add ListItem.
foreach (ListItem LI in listBoxFrom.Items)
{
if (LI.Selected)
listBoxTo.Items.Add(LI);
}
To add in to 2nd listbox and remove that from the first listbox you can use below code:
int[] indices = listBoxFrom.GetSelectedIndices();
for (int i = indices.Length - 1; i >= 0; i--)
{
ListItem LI = listBoxFrom.Items[indices[i]];
listBoxTo.Items.Add(LI);
listBoxFrom.Items.RemoveAt(indices[i]);
}
put your No items selected message where you require.
I got answer of my own question.
i have to set my DataRowView object
if (listBoxSelectToLedger.Items.Count > 0)
{
for (int i = 0; listBoxSelectToLedger.Items.Count > i; i = 0)
{
listBoxSelectToLedger.Items.Remove(listBoxSelectToLedger.Items[i].ToString());
}
}
if (listBoxSelectFromLedger.SelectedItem != null)
{
foreach (DataRowView objDataRowView in listBoxSelectFromLedger.SelectedItems)
{
listBoxSelectToLedger.Items.Add(objDataRowView["item_name"].ToString());
}
}
else
{
MessageBox.Show("No Item selected");
}

Delete 4 ListBox items by selecting one

I was wondering but I have 4 listboxes and what I was wondering is how would I delete all 4 of the items by just selecting one item?
As you can see here this is the part that deletes the selected item but how would I delete all 4 items in my listbox if I just selected the "seriesName" one.
for (int x = lstb_seriesName.SelectedIndices.Count - 1; x >= 0; x--)
{
int a = lstb_seriesName.SelectedIndices[x];
lstb_seriesName.Items.RemoveAt(a);
}
Here's my code for the delete button.
private void btn_Delete_Click(object sender, EventArgs e)
{
if (lstb_seriesName.SelectedItems.Count <= 0)
{
MessageBox.Show("You need to select an item to delete first!");
}
else
{
for (int x = lstb_seriesName.SelectedIndices.Count - 1; x >= 0; x--)
{
int a = lstb_seriesName.SelectedIndices[x];
lstb_seriesName.Items.RemoveAt(a);
}
System.IO.StreamWriter DeleteFileData = new System.IO.StreamWriter(sPath);
foreach (var item in lstb_seriesName.Items)
{
DeleteFileData.WriteLine(item);
}
foreach (var item in lstb_seriesDay.Items)
{
DeleteFileData.WriteLine(item);
}
foreach (var item in lstb_seriesTime.Items)
{
DeleteFileData.WriteLine(item);
}
foreach (var item in lstb_seriesActive.Items)
{
DeleteFileData.WriteLine(item);
}
DeleteFileData.Close();
MessageBox.Show("Program deleted!");
}
}
The only way to do this is if you can guarantee that they are all in the same order.
In which case you could take the IndexOf(item) and use the index value to delete the other list items by index.
Otherwise, you need some way to link/relate these guys to each other.
Edit Per Request:
private void btn_Delete_Click(object sender, EventArgs e)
{
if (lstb_seriesName.SelectedItems.Count <= 0)
MessageBox.Show("You need to select an item to delete first!");
else
{
var indexesToRemove = lstb_seriesName.SelectedIndices;
foreach(var index in indexesToRemove)
{
lstb_seriesName.Items.RemoveAt(index);
lstb_seriesDay.Items.RemoveAt(index);
lstb_seriesTime.Items.RemoveAt(index);
lstb_seriesActive.Items.RemoveAt(index);
}
MessageBox.Show("Program deleted!");
}
}

How do I move items from one gridview to another gridview?

I have two gridviews, and when the user highlights a row on the first gridview and clicks a button, it should move to the second gridview.
When I click on the button that record gets added but it only add the last row I've selected (if I select 20 rows, only the last gets added).
All records that are selected should be moved.
How do I do this in ASP.NET?
private void button1_Click_1(object sender, EventArgs e)
{
DataGridViewRow dr = dataGridView1.SelectedRows[0];
dtItems.Columns.Add("city_ID");
dtItems.Columns.Add("city_Name");
dtItems.Columns.Add("status");
dtItems.Columns.Add("date");
if (dataGridView1.Rows.Count > 1)
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value != null)
{
DataRow row;
row = dtItems.NewRow();
row["city_ID"] = dataGridView1.Rows[i].Cells[1].Value.ToString();
row["city_Name"] = dataGridView1.Rows[i].Cells[2].Value.ToString();
row["status"] = dataGridView1.Rows[i].Cells[3].Value.ToString();
row["date"] = dataGridView1.Rows[i].Cells[4].Value.ToString();
dtItems.Rows.Add(row);
}
}
}
Form2 frm = new Form2(dtItems);
frm.ShowDialog();
}
In Form2 copy this code:
public Form2(DataTable dtIt)
{
dtItems = dtIt;
InitializeComponent();
}
private void AddEmptyRows()
{
for (int i = 1; i <= 5; i++)
{
dataGV.Rows.Add();
}
}
private void Form2_Load(object sender, EventArgs e)
{
AddEmptyRows();
for (int i = 0; i < dtItems.Rows.Count; i++) {
dataGV.Rows[i].Cells[0].Value = dtItems.Rows[i]["city_ID"];
dataGV.Rows[i].Cells[1].Value = dtItems.Rows[i]["city_Name"];
dataGV.Rows[i].Cells[2].Value = dtItems.Rows[i]["status"];
dataGV.Rows[i].Cells[3].Value = dtItems.Rows[i]["date"];
}
dataGV.Enabled = true;
}

Categories

Resources