How to select Row without key - c#

There are many ways to select a row programmatically e.g. by if we know row index, or if we know the Primary-key-like column (column that contain unique value).
Now, when I'm creating my custom control, I wonder is there another way to select row using another way?
Let's say I backup the selected record in each OnSelectionChanged event using variable named BackupRow.
then when I sort the data using columnheader click, in OnSorted I want to select the grid using the BackupRow.
Is something like that possible?
Thank you.

No other method.. For solution to your problem you could.
Backup indices(in an integer list or array), no need to backup complete rows.. if you do need you do it as well. But you need to Backup indices any case.. And select rows form sorted grid on the base of those (backup) indices

if your data count never change and you can exactly know sorting algorithm its possible but not trustful for the true value..
as a pseudo-example : You have rows A-B-C-D and current is B..
if rows sorted ascendant (A to Z or 0 to 100) and then you sorted descendant(Z to A or 100 to 0) then its simply :
suppose your,
total rows = 45;
current row index for ascendant sort = 30;
sort descendant();
your current's new index = (total row - ascendant sorted row index)-1;
//-1 is for index [0] correction
your current's new index = 45-30 -1;
your current's new index = 14;
And an alternative way :
implement your own sort algorithm and create a delegate / pointer - i can't imagine which can be better right now-
then while each sort operation investigate your selected row and select again..
but as i said these are nost trustful ways..and noone never prefer / suggest..
Another Opinion :
Your question is not clear for me..this opinion is for clearer the possible misunderstood..
if you want "when user selects a row or sorts from-on a column value, the complete row cells get highlighted automatically- shown to user as Selected"
then its under datagridview's SelectionMode Property..
dataGridView1.SelectionMode = FullRowSelect;

Related

Removing column based on the content of the cells

I need to delete the whole column in a DataGridView based on a certain condition. My DataGridView columns consists of numbers (1,2 and 3) the condition would be to delete all columns that does not contain (1,2 and 3). For Example if the column has only (1 and 3) it should be deleted.
How do I Overcome this? as many threads I went through only cover when you are certain of an index like below.
myGridView.columns.RemoveAt(index);
Some suggest hiding columns and thats not what I want, I want to completely remove the column from the DataGridView.
While it's better to do the job using data source of the DataGridView, but if the control is not bound to a data source, you can also use linq to get values from columns and check for some criteria, for example:
dgv1.Columns.Cast<DataGridViewColumn>()
.ToList().ForEach(c =>
{
var values = dgv1.Rows.Cast<DataGridViewRow>().Where(r => !r.IsNewRow)
.Select(r=>r.Cells[c.Index].Value).ToList();
if (!values.Contains(1)) //your custom criteria
dgv1.Columns.Remove(c);
});
Here is a really simple test. Load dgv1 this way:
dgv1.ColumnCount = 2;
dgv1.Rows.Add(1, 2);
dgv1.Rows.Add(3, 4);
Then use above code to delete columns and it just removes the last column.

c# add objects to table rows dynamiclly

I am trying to do something like this but I don't know how:
I have a table in c# which I increase and decrease during runtime.
Each row contains data, that is being parsed from an object.
I want to get an access to the object that the line is parsing, some a pseudo of it would be:
if (table.row.object == selectedObject)
I can't do it from the row number or something because the rows are being removed and inserted, each time with different objects.
any ideas, please?
EDIT: I am using TableLayoutPanel to work with a table, and this is how I add rows and removes them:
I am adding rows to the table dynamically, I have set of buttons and when I click one it deletes all old rows from the table and adds new rows that are related to this button.
This is the way I add new rows:
tlp.RowCount++;
tlp.RowStyles.Add(new RowStyle(SizeType.AutoSize));
tlp.Controls.Add(new Label() { ... }, cellIDX, rowIDX);
// adding more columns //
and to remove old rows I loop through all rows from bottom to top, removes all related controls of the current cell, then I remove style and row num like so:
tlp.RowStyle.RemoveAt(rowNum);
tlp.RowCount--;
thank you
you can also see a previous question I had related to this subject:
C# change table row color when mouse hover
You can try having a new column in the table (call it original_row_no) and set the row values into that, before you start your insertion/deletion process. That way you can reference the row directly (this is in response to your final line which says "I can't do it from the row number or something because the rows are being removed and inserted, each time with different objects."
A better way is to have a unique id in the table and run your references against that.
It is much more easier to help if you show the code you are trying.

Issue using counters in datagridview c#

I have datagridview table. Whenever a user selects row and click 'Update Counter' button, counter value changes to 1 at top corner of window.
Now if a user selects the same row, the counter is updated incrementally which I don't want. I don't want counter to update on same row selection.
My code -
Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
for (int i = 0; i < selectedRowCount; i++)
{
// need to insert condition so that counter is not updated when same row is selected again.
Counter.Text = Convert.ToString(i + 1);
}
}
I new to C# development, please provide changes.
Without seeing the rest of the code, or really understanding what you are doing (is this list going to change, what is the counter, can you identify the selected row easily?), all I can really suggest is maintaining a list of selected rows and checking that before updating the counter.
For example, in the for each:
if (selectedRows.Contains(rowIdentifier)) continue;//if you want to keep looping, otherwise break;
You may use the Tag property of the DataGridViewRow to identify rows already selected.
foreach (DataGridViewRow r in dataGridView1.SelectedRows)
if (r.Tag!=null) { Counter.Text=int.Parse(Counter.Text)+1 ; r.Tag=True ; }
I would add a condition statement that checks to see if the variable is dirty or has already been updated. This sounds similar to a concurrency issue or checking concurrency, I'm sure if you searched for ways to resolve concurrency issues the logic used would be similar. I agree with #johnc
I would utilize the onclick event then disable the ability to click the same row again.
OR use some other unique property of the row and check against it.
if(row.uniqueProperty == -1)
{
Counter.Text = Convert.ToString(i + 1);
}
Basically, I created a SQL table storing all values from selected row. If selected row value is something already there in the table, the counter doesn't get updated while the counter gets updated when unique row is selected.

Datagridview and checkboxlist

I have a question. Let's say i have a checkboxlist with the ingredieints for a cake and i choose not just one but more ingredients (3-4). I want to save this in datagridview. Can datagridview show more than one ingredient or is this not possible ?
You see i'm making an application for bakeries and for ordering cakes you will choose the type of cake and adding(toppings) and the number of cakes you want. Then I would like to save this to datagridview, or show this in dgv and then when I would finish with ordering i would just click on send button in dgv and all the orders i made would be sent to an email. I hope you understand what i want.
Even in its simplest uses a DataGridView is a 2-dimesional container; a 'grid', so you can have as many rows and columns as you want.
If you want to display them all in row you should first try to estimate the maximum number of ingredients. Then you add this number of columns to the target DGV.
Then add a row and fill its column cells with the ingredients.
In case you come across a cake with even more ingredients that would't be a problem either as you can always add more columns.
Empty cells are no problem, just make sure to always check for null values.
By the way, cells are quite powerful and you can have a tag for each single cell, so you can add as many data of any complexity to the cell beyond its mere value!
Here is some simple sample code:
while (dataGridView1.ColumnCount < checkedListBox1.CheckedItems.Count)
dataGridView1.Columns.Add("", "");
int newRow = dataGridView1.Rows.Add();
int item = 0;
foreach ( object o in checkedListBox1.CheckedItems)
{
dataGridView1[item, newRow].Value = o.ToString();
item ++;
}

Rearranged columns in C#

How can I get the rearranged columns out of a datagridview in C#? I need to get all the columns currently being displayed in order. I can get the default columns order by setting datagridview.AutoGenerateColumns=false but I get the same old order even after I've rearranged the columns in my table.
Edit: Basically what I need is to be able to iterate through all the columns of a datagridview based on their display index
Thanks
Use the DisplayIndex property of your DataGridView Columns.
The DisplayIndex property:
Gets or sets the display order of the
column relative to the currently
displayed columns.
Edit:
It's ugly, and I'm sure people are going to point and laugh, but this might give you a rough idea on one implementation to improve upon.
Create a DGV with three columns and set their DisplayName properties like so:
dataGridView1.Columns[0].DisplayIndex = 1;
dataGridView1.Columns[1].DisplayIndex = 2;
dataGridView1.Columns[2].DisplayIndex = 0;
Add the following code to loop through all the columns access the columns in the DGV in their DisplayIndex order:
for (int index = 0; index < dataGridView1.Columns.Count; index++) {
foreach (DataGridViewColumn c in dataGridView1.Columns) {
if (c.DisplayIndex == index) {
// You've got your next column.
Console.WriteLine(c.Name);
}
}
}
How are you selecting? SELECT *? You need to specify the columns in the order you want them.
Have you rearranged their order in the ItemTemplate section of your grid? You can also change the order via the context menu for a GridView, alternative you can change your SQL statement and make sure autogenerate is off

Categories