My form1 has datagridview, that is populated by a dataset.

I want to pass the selected value of the datagridview to my other form which is form2. How could I do this?

Dani AI

Generated

The constructor pattern used by is a simple, valid way to hand the selected record to an edit form. For production-quality code, favor a few improvements: validate the selection (CurrentRow can be null or not reflect the user selection), set DataGridView.SelectionMode = FullRowSelect, and use TextBox.ReadOnly = true for the primary key (better UX than disabling the control). Avoid building SQL by concatenating values—use parameterized commands to prevent SQL injection and parsing errors.

A robust pattern is either pass a small model/DataRowView into the edit form (so no extra DB round-trip) or pass the PK and load the record with a parameterized query inside the edit form. Example patterns:

// safe selection (C#)
if (dataGridView1.SelectedRows.Count == 0) return;
var keyCell = dataGridView1.SelectedRows[0].Cells["Student_No"].Value;
if (keyCell == null || keyCell == DBNull.Value) return;
string studentNo = keyCell.ToString();

// load with parameterized command
using(var cn = new SqlConnection(connString))
using(var cmd = new SqlCommand("SELECT Last_Name, First_Name FROM Student WHERE Student_No = @id", cn))
{
    cmd.Parameters.AddWithValue("@id", studentNo);
    cn.Open();
    using(var rdr = cmd.ExecuteReader())
    {
        if (rdr.Read()) { txtLastName.Text = rdr["Last_Name"].ToString(); /* ... */ }
    }
}

NumericUpDown.Value is a decimal; convert explicitly (for example, use CInt/Convert.ToInt32 or a cast) depending on desired rounding. For the VB symptom (always getting the first row) usually means the code is using Rows(0) or CurrentRow; use SelectedRows and ensure SelectionMode = FullRowSelect and MultiSelect = False. As noted, exposing a constructor or method on the edit form is idiomatic, and as reminded, conversions must be explicit.

Recommended Answers

All 6 Replies

Please be specific. in what format do you want to pass the data? are you gonna store them in local variables or you want to pass them into a form control? one way could be to make a method in the other form and pass the arguments which you need to it, then update whatever you want to update in the next form or just pass it with reference

I've tested the following and it works.

My form1 has a gridview and a button for edit

private void editbutton_Click(object sender, EventArgs e)
        {
            EditStudent EditStudent = new EditStudent(Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value));
            EditStudent.Show();
        }

My EditStudent is my second form which has textboxes for editing. The primary key(student number), which is the cells[0] to be pass to my textbox1 in second form. My textbox1 in the second is disabled.

public EditStudent(string srno)
        {
            InitializeComponent();

            textBox1.Text = srno;
        }

Then I use a sql select statement to populate the other textboxes for editing.

SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Student WHERE Student_No = '"+textBox1.Text+"'", con);
            da.Fill(ds);
            DataTable dt = new DataTable();
            dt = ds.Tables[0];

            if (dt.Rows.Count > 0)
            {
                textBox2.Text = dt.Rows[0]["Last_Name"].ToString();
                textBox3.Text = dt.Rows[0]["First_Name"].ToString();
                comboBox1.SelectedItem = dt.Rows[0]["Department"].ToString();
                comboBox2.SelectedItem = dt.Rows[0]["Course"].ToString();
                textBox4.Text = dt.Rows[0]["Address"].ToString();
                textBox5.Text = dt.Rows[0]["Contact_No"].ToString();
            }

Do you think this is a good or maybe a fair approach?

commented: A good way to provide a details view. +1

personally its good, as long as it works and doesnt violate any security / code quality. you know what they say about coding bra, there can only be standards but there arent any rules as to how you should do something. goodluck with your code. if you got any question feel free to post them here for some comments.

There's one error though.

I can't simply convert the numericupdown.value to string. It says decimal cannot implicitly convert to string. I have posted a separate thread about this, but please tell me if you know how to fix it.

AngelicOne Generally when it tells you that you cannot implicitly convert a variable to another type there's a simple solution :)

What cannot convert implicitly must be converted explicitly. What this means is... Rather than use something like

string varString1 = someInteger;

Which would be an implicit cast from integer to string you would use:

//Option 1
string varString1 = someInteger.ToString();
//Option 2
string varString1 = Convert.ToString(someInteger);

The first method works great for strings because virtually every data type has a .ToString() method. Many of the other possible conversions, however, do require the 2nd option :)

I'm not specifically seeing the variable conversion that's causing your issue based on the source code you provided so I can't give a specific example to match the error (I could just be missing it) but I hope this helps :)

commented: well written +3

would anybody have this code in VB, my insertion to the textboxes on another form works but it goes to the first person in the grid even though i selected the third person
Thanks Steve

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.