如何检索在datagridview中选择的行c#

时间:2017-03-17 17:44:40

标签: c# .net datagridview

我有一个datagridview包含一个列复选框

enter image description here

现在我希望当我从复选框中的datagridview中选择一行时,我单击按钮保存我检索该行以及一些值 我如何取悦并提前感谢

MY WINFORMS如下:

enter image description here

代码如下:

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

namespace gestion_attachements_decomptes
{
    public partial class ajouter_attachement : Form
    {

        public ajouter_attachement(string num_marche,string libelle_fournisseur)
        {
            InitializeComponent();
            textBox1.Text = num_marche;
            textBox2.Text = libelle_fournisseur;
        }


        private void ajouter_attachement_Load(object sender, EventArgs e)
        {
            //désactiver button enregistrer 
            button1.Enabled = false;

            //ajouter checkbox dans datagrid view 
            DataGridViewCheckBoxColumn chk = new DataGridViewCheckBoxColumn();
            chk.HeaderText = "";
            chk.Name = "CheckBox";
            dataGridView2.Columns.Add(chk);

            dataGridView2.AllowUserToAddRows = false;
            dataGridView2.AllowUserToDeleteRows = false;


        }




        private void button4_Click(object sender, EventArgs e)
        {

            Program.cmd.CommandText = "select * from bon_reception_marche where  Date_reception between '" + dateTimePicker1.Value.Date + "' and '" + dateTimePicker2.Value.Date + "'";
            Program.dr = Program.cmd.ExecuteReader();
            while (Program.dr.Read())
            {
                dataGridView2.Rows.Add(Program.dr[2], Program.dr[3], Program.dr[5], Program.dr[6], Program.dr[7], Program.dr[8], Program.dr[9], Program.dr[10], Program.dr[11], Program.dr[12]);
            }
            Program.dr.Close();

        }

        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 10/*myColumn*/ && e.RowIndex >= 0 /*myRow*/)
            {
                button1.Enabled = true;
            } 
        }



        private void button1_Click(object sender, EventArgs e)
        {
            // index of the checkbox column
            int colIndex = dataGridView2.Columns["CheckBox"].Index;

            var rows = dataGridView2.Rows
                        .Cast<DataGridViewRow>()
                        .Where(row => row.Cells[colIndex].Value != null)
                        .Where(row => (bool)row.Cells[colIndex].Value)
                        .ToList();
            // loop through entire DataGridView and see if checkbox is checked
            foreach (DataGridViewRow row in dataGridView2.Rows)
            {
                // checked if the cell's value is true
                if ((bool)rows.Cells[colIndex].Value)
                {
                    MessageBox.Show("ok");
                }
            }
            ////if (dataGridView2.Columns == 10)
            ////{
            ////    double montant = Convert.ToDouble(dataGridView2.CurrentRow.Cells["Montant"].Value);
            ////}
            //int id_br = Convert.ToInt32(  dataGridView2.CurrentRow.Cells["Id_bon_reception_marche"].Value);
            //Program.cmd.CommandText = "";
            //Program.cmd.ExecuteNonQuery();
            //MessageBox.Show("c'est ajouté avec succés");
            //Program.cmd.Parameters.Clear();
        }



    }
}

1 个答案:

答案 0 :(得分:0)

// give a method to be run when the save button is clicked
saveButton.Click += saveButton_Click;


// implementation of the saveButton's above click event
private void saveButton_Click(object sender, EventArgs e)
{
    // index of the checkbox column
    int colIndex = dataGridView1.Columns["checkBoxColumn"].Index;

    List<DataGridViewRow> rows = new List<DataGridViewRow>();
    // loop through entire DataGridView and see if checkbox is checked
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        // checked if the cell's value is true
        if (row.Cells[colIndex].Value != null && (bool)row.Cells[colIndex].Value)
            rows.Add(row);
    }

    // do whatever processing here with rows
}

除了foreach循环之外,您只需使用LINQ来描述您想要的内容(确保将using System.Linq;放在顶部)。

int colIndex = dataGridView1.Columns["checkBoxColumn"].Index;
var rows = dataGridView1.Rows
    .Cast<DataGridViewRow>()
    .Where(row => row.Cells[colIndex].Value != null) 
        && (bool)row.Cells[colIndex].Value)
    .ToList();

// do whatever processing here with rows

编辑:

private void button1_Click(object sender, EventArgs e)
{
    int colIndex = dataGridView2.Columns["CheckBox"].Index;
    try
    {
        var rows = dataGridView2.Rows
            .Cast<DataGridViewRow>()
            .Where(row => row.Cells[colIndex].Value != null
                && row => (bool)row.Cells[colIndex].Value)
            .ToList();

        foreach(DataGridViewRow row in rows)
            insertRowData(row);

        MessageBox.Show("c'est ajouté avec succés");
    }
    catch (FormatException)
    {
        MessageBox.Show("Only input numbers into the table!", 
                        "Only Numbers", MessageBoxButtons.OK);
    }
    catch (Exception)
    {
        MessageBox.Show("There was an error while saving!", 
                        "Error", MessageBoxButtons.OK);
    }
}

private void insertRowData(DataGridViewRow row)
{
    double montantValue = row.Cells["Montant"].Value != "" ? 
        Convert.ToDouble(row.Cells["Montant"].Value) : 0;
    int id_br = Convert.ToInt32(row.Cells["Id_bon_reception_marche"].Value);

    Program.cmd.Parameters.Clear();
    // change your sql to however you need to insert it
    Program.cmd.CommandText = "INSERT INTO tableName (montantColumn, idColumn) VALUES (@montant, @id);";
    Program.cmd.Parameters.AddWithValue("@montant", montantValue);
    Program.cmd.Parameters.AddWithValue("@id", id_br);
    Program.cmd.ExecuteNonQuery();
}