views:

2815

answers:

6

Hi,

I'm trying to select the first row where the cell value starts with the same keychar the user pressed. That's the part that is giving me trouble.

Here's how I'm handling the event (updated with working solution):

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsLetter(e.KeyChar))
    {
        for (int i = 0; i < (dataGridView1.Rows.Count); i++)
        {
         if (dataGridView1.Rows[i].Cells["Name"].Value.ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
         {
          dataGridView1.Rows[i].Cells[0].Selected = true;
          return; // stop looping
         }
        }
    }
}

I'm sure it's something simple that I'm overlooking, but for the life of me can't figure out what it is.

EDIT

Updated the code with solution applied

+3  A: 

Might be a case issue, is the Value in Cells["Name"] start with a capital letter? Try using ToUpper or ToLower on both; or you could try StartsWith(e.KeyChar, true) to ignoreCase. If you are trying to select the row, you'll want to do dataGridView1.Rows[i].Selected = true

SwDevMan81
You're right, it's the case of the character that was causing the problem
Johann J.
+1  A: 
if (Char.IsLetterOrDigit(e.KeyChar))
{
    foreach (DataGridViewRow dgvRow in myDgv.Rows)
    {
        if (dgvRow.Cells["ColumnName"].FormattedValue
            .ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
        {
            dgvRow.Selected = true;
            break;
        }
    }
}

If the DGV is set up to allow Multi-Select then you'd obviously want to deselect any existing selection.

frou
Thanks for your sample, it gives me an alternative (a bit cleaner looking too).
Johann J.
+1  A: 

This is a VS2008 VB.NET DataGridView extension meant to do kind of what you are doing but using a TextBox for searching information (not designed with case in mind but could easily be added). This extension works so perhaps there is something that might be helpful. I did notice that your code selects a row using select where mine uses CurrentCell.

    <Runtime.CompilerServices.Extension()> _
Public Function PartSeek(ByVal GridView As DataGridView, ByVal ColumnName As String, ByVal Value As String, ByVal Part As Boolean) As Boolean
    Dim Located As Boolean = False

    If GridView.Columns.Contains(ColumnName) Then
        Dim SingleRow As DataGridViewRow
        If Part Then
            SingleRow = (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() _
                         Where Rows.Cells(ColumnName).Value.ToString().Contains(Value)).FirstOrDefault
        Else
            SingleRow = (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() _
                         Where Rows.Cells(ColumnName).Value.ToString() = Value).FirstOrDefault
        End If
        If Not IsNothing(SingleRow) Then
            If GridView.CurrentCell.RowIndex <> SingleRow.Index Then
                GridView.CurrentCell = GridView(0, SingleRow.Index)
            End If
            DirectCast(GridView.Parent, Form).ActiveControl = GridView
            Located = True
        End If
        Return Located
    Else
        Throw New Exception("Column '" & ColumnName & "' not contained in this DataGridView")
    End If

End Function
A: 

Can some one post the whole solution for this issue i need it to much, please i need help with this. I need an C# solution on VS 2005

AXheladini
I updated the question with working code, hope that was what you were asking for.
Johann J.
Oh, and if you're looking for a C# version of kevininstructor's VB code, just paste it into http://www.developerfusion.com/tools/convert/vb-to-csharp/ and press convert :)
Johann J.
A: 

Where to put this code, on PageLoad function or ...

Any Help Here

i put the code like a function but is not workingg what I am doing wrong ??

`using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Globalization;

namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }

    private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetter(e.KeyChar))
            if (Char.IsLetterOrDigit(e.KeyChar))
            {
                foreach (DataGridViewRow dgvRow in dataGridView1.Rows)
                {
                    if (dgvRow.Cells["Emri"].FormattedValue
                        .ToString().StartsWith(e.KeyChar.ToString(), true, CultureInfo.InvariantCulture))
                    {
                        dgvRow.Selected = true;
                        break;
                    }
                }
            }

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'gRIDVIEWDataSet.tbl_Products' table. You can move, or remove it, as needed.
        this.tbl_ProductsTableAdapter.Fill(this.gRIDVIEWDataSet.tbl_Products);




    }



}

}`

AXheladini
How is it not working? What errors do you get? Did you add the event yet?Put this in Form1_Load if you haven't created the event: // add eventhandler fyrir keypress this.dataGridView1.KeyPress += new KeyPressEventHandler(dataGridView1_KeyPress);
Johann J.
Can you show me the whole process where to add this eventhandler and other stuff, i dont get errors only is not working, i type keys in keyboard and i get nothing ?
AXheladini
ok its working now. Great i added the event in Form Load no is working good. THANKS
AXheladini
I'm glad you worked it out
Johann J.
A: 

please is it possible to do thesame thing in wpf datagrid?

don