Avatar of RockBaby
RockBabyFlag for Singapore

asked on 

Datagridview

Hi,

I'm creating a datagridview. I'm able to get data from database by coding. Now i need to edit the record.
Let's say i have a contextMenuStrip with Insert, Edit and Delete function. Then when i select the row right click on it and able to edit. How do i code tat selecting and editing paricular?

Regards,
RockBaby
C#Programming Languages-Other

Avatar of undefined
Last Comment
ab_khadilkar
Avatar of vbturbo
vbturbo
Flag of Denmark image

Hi RockBaby

Why not just bind the grid to a dataset ,that way you get Insert, Edit and Delete functionallity in the grid.

When done , just update the modifications to the datasource.

vbturbo
Avatar of RockBaby
RockBaby
Flag of Singapore image

ASKER

how to bing the grid to dataset?
Avatar of RockBaby
RockBaby
Flag of Singapore image

ASKER

but i need to do like select the row of the record from dataviewgrid and click on the edit or delete button.
How to do that?
Avatar of vbturbo
vbturbo
Flag of Denmark image

OleDb.OleDbConnection con = new OleDb.OleDbConnection();
DataSet ds = new DataSet();
OleDb.OleDbDataAdapter daParent;
string sql;

private void Form1_Load(object sender, System.EventArgs e)
{
 con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\\Test.mdb";
 sql = "SELECT * FROM mytable";
 con.Open();
 daParent = new OleDb.OleDbDataAdapter(sql, con);
 daParent.FillSchema(ds, SchemaType.Mapped, "mytable");
 daParent.Fill(ds, "mytable");
 con.Close();
 Datagridview1.DataSource = ds.Tables["mytable"];
}

private void btnSave_Click(object sender, System.EventArgs e)
{
 OleDb.OleDbCommandBuilder cb = new OleDb.OleDbCommandBuilder(daParent);
 daParent.Update(ds, "mytable");
 MessageBox.Show("Data updated");
}

vbturbo
Avatar of vbturbo
vbturbo
Flag of Denmark image

Here you bind the grid
Datagridview1.DataSource = ds.Tables["mytable"];

now delete,add , modify any row in the grid

Then save the changes back to the database.
Avatar of vbturbo
vbturbo
Flag of Denmark image

One precondition though ! your table has to have a primary key.
Avatar of vbturbo
vbturbo
Flag of Denmark image

Else here is how you collect the clicked row's data e.g. for txtbox's , contextMenuStrip's delete method ect..

private void myDataGridView_CellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
 DataGridViewRow dr = myDataGridView.CurrentRow;
 string CustomerId = "";
 string CustomerName = "";
 string CustomerAddress = "";
 int Rowno;
 CustomerId = dr.Cells["CustomerId"].Value.ToString();
 CustomerName = dr.Cells["CustomerName"].Value.ToString();
 CustomerAddress = dr.Cells["CustomerAddress"].Value.ToString();
 Rowno = DataGridView.Rows[e.RowIndex]
}

vbturbo
Avatar of jinn_hnnl
jinn_hnnl
Flag of Netherlands image

Bind to DataSet is the best way for your situation. In case you wanna select row... or get any value out of the cell, you might try out hitTest method (this is the short example version):

Define your DataGrid event - MouseDown

private void dataGrid1_MouseDown
(object sender, System.Windows.Forms.MouseEventArgs e)
{
   Console.WriteLine();
   System.Windows.Forms.DataGrid.HitTestInfo myHitTest;
   // Use the DataGrid control's HitTest method with the x and y properties.
   myHitTest = dataGrid1.HitTest(e.X,e.Y);
   Console.WriteLine(myHitTest);
   Console.WriteLine("Column " + myHitTest.Column);
   Console.WriteLine("Row " + myHitTest.Row);
   Console.WriteLine("Type " + myHitTest.Type);
   Console.WriteLine("ToString " + myHitTest.ToString());
   Console.WriteLine("Hit " + myHitTest.Type.ToString());
}

this way you know index of clicked cell, row, header .... and easily get value out of it like ... if you wanna take the primary key and use it somewhere, just:

((DataTable)dataGrid1.DataSource.Rows[myHitTest.Row]["ColumnName"].ToString();

Hope this will help you find it easy to use DataGrid

JINN,
Avatar of vbturbo
vbturbo
Flag of Denmark image

JINN

<<I'm creating a datagridview.
I think that HitTestInfo is for datagrid 2003 and not the datagridview.

Perhaps i missed something ? -:]

vbturbo
Avatar of jinn_hnnl
jinn_hnnl
Flag of Netherlands image

ohh u right, my bad ... I didn't notice that >.<
Avatar of RockBaby
RockBaby
Flag of Singapore image

ASKER

hi.

i test the cellclick thing
private void dataGridView1_cellClick(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
     MessageBox.Show("Clicked");
}

it does not work. when i click on my datagridview cell, the dialogbox does not appear.
Avatar of RockBaby
RockBaby
Flag of Singapore image

ASKER

ok, i manage to show the messagebox.. somehow...

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            MessageBox.Show("Click");

             DataGridViewRow dr = dataGridView1.CurrentRow;
             int Rowno;
             Rowno = DataGridView.Rows[e.RowIndex];
        }

error:
error CS0029: Cannot implicitly convert type 'System.Windows.Forms.DataGridViewRow' to 'int'
Avatar of vbturbo
vbturbo
Flag of Denmark image

Rowno = Int.Parse(DataGridView.Rows[e.RowIndex]);
ASKER CERTIFIED SOLUTION
Avatar of vbturbo
vbturbo
Flag of Denmark image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of ab_khadilkar
ab_khadilkar
Flag of India image

      This works, although you might need some more error-checking and it only selects the cell (you probably wanted to select the whole row ... you can probably figure out that part ... I didn't have time to mess with it any more).

 

But, here's what I did. In the event handler for the Grid's CellMouseDown event, put this code (hopefully you won't mind  C# code here ... it should be an easy translation for you):
 private void iddgDispatchList_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                iddgDispatchList.CurrentCell = iddgDispatchList.Rows[e.RowIndex].Cells[e.ColumnIndex];           
        }    

Open in new window

C#
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo