0

Using the following code the first row in SQL is printed only, How can I print selected row from DataGridView in C# with SQL:

public partial class PrintScreen : Form 
{ 
    SqlConnection con = new SqlConnection(@"Server = TEST;DataBase=Registration;Integrated Security=true;");
    SqlDataAdapter da;
    DataTable dt = new DataTable();

    public PrintScreen()
    {
       InitializeComponent();
       da = new SqlDataAdapter("select * from data_graduation", con);
       da.Fill(dt);
       this.dataGridView1.DataSource = dt;
    }

    private void Print_ys_ar_cert_Click(object sender, EventArgs e)
    {
        Print_ys_ar_cert frm = new Print_ys_ar_cert();
        da = new SqlDataAdapter("select * from data_graduation where ID_gra = '" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'", con);
        da.Fill(frm.RegistrationDataSet1.data_graduation);
        frm.reportViewer2.RefreshReport();
        frm.Show();
    }
}
3
  • Your query is likely only returning one row. Commented Jul 27, 2016 at 20:37
  • Because you passed the value of Cells[0] of first row. You need to pass Cells[0] of selected row Commented Jul 27, 2016 at 20:38
  • Also since you have loaded the row from database once, you don't need to load it again from database, you can simply add it to the data table which is data source of the report. Commented Jul 27, 2016 at 20:55

1 Answer 1

1

Currently you are passing value of Cells[0] of first row of the grid, you need to pass value of selected row:

if(dataGridView1.SelectedRows.Count>0)
{
    var selectedValue = dataGridView1.SelectedRows[0].Cells[0].ToString();
    //rest of code
}

Since you have loaded the row from database once, you don't need to load it again from database, you can simply add it to the data table which is data source of the report this way:

var row = ((DataRowView)(dataGridView1.SelectedRows[0].DataBoundItem)).Row;
frm.RegistrationDataSet1.data_graduation.Rows.Add(row.ItemArray);
//rest of code
Sign up to request clarification or add additional context in comments.

1 Comment

@oks2016 Since you are new to stackoverflow, you should know you can accept an answer by click on check mark near the answer. For more information about how accepting answers works see this post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.