简体   繁体   中英

insert to database checked row in datagridview in c# using ado.net

Code:

int i = 0;
List<int> ChkedRow = new List<int>();
for (i = 0; i <= dataGridView1.RowCount; i++)
{
    if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "yes")
    {
        ChkedRow.Add(i);
    }
}

if (ChkedRow.Count == 0)
{
    MessageBox.Show("Select one checkbox");
    return;
}

foreach (int j in ChkedRow)
{
    try
    {
        Query = "Insert into dbo.tbl_Class(Class_Name,Category,Description,Item) values ('" + txtname.Text + "','" + cbo_cat.Text + "','" + txtdesc.Text + "','" + dataGridView1.Rows[j].Cells[1].Value.ToString() + "')";
        SqlCommand cmd = new SqlCommand(Query, con);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
MessageBox.Show("Records successfully inserted");

I want to save in sql the row that i selected in my datagridview but I'm having a error in this line "if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "yes")" . and I don't know why. can you please help me with this? or suggest another code or another approach? Please help.

I'm not too sure what error you are getting but you will definitely get in IndexOutOfRange exception or something similar because of the way you are iterating through the rows here...

for (i = 0; i <= dataGridView1.RowCount; i++)

RowCount returns the total amount of rows, however, you are accessing a zero-based index which will throw the above mentioned xception as soon as you hit the last iteration. So, you have to change the evaluation expression in the for loop to exclude the last iteration as below...

for (i = 0; i < dataGridView1.Rows.Count; i++)

Update

Based on your comment, since you're getting a NullReferenceException , you should make sure that the value of the cell has been set to something else than null as below...

var row = dataGridView1.Rows[i];
if (!string.IsNullOrEmpty(row.Cells[0].Value) && row.Cells[0].Value.ToString() == "yes")
{
    ChkedRow.Add(i);
}

also try using dataGridView1.Rows.Count instead of the RowCount property

have u tried with columnname instead of int index?

if (dataGridView1.Rows[i].Cells["ColumnName"].Value.ToString() == "yes")
            {
                ChkedRow.Add(i);
            }

try this,

foreach (GridViewRow grdRow in dataGridView1.Rows)
{
CheckBox chk = new CheckBox();
int count=0;
chk = (CheckBox)grdRow.FindControl("check box name");
if (chk != null && chk.Checked == true)
{ 
    //write code for insesrt
    count++;
}
}

if(count==0)
{
   MessageBox.Show("Select one checkbox");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM