I am needing that if there is no CheckBox selected in the DataGridView the button Uno and the button Varios are disabled.
If a single CheckBox is selected, the button Uno is enabled and the button Varios disabled.
And if there is more than one CheckBox selected, the button Uno is disabled and the button Varios is enabled.
But, the following happens:
The code I use is the following:
public Form1()
{
InitializeComponent();
btnUno.Enabled = false;
btnVarios.Enabled = false;
}
To enable and disable the buttons:
private void dtgTitulo_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int contador = 0;
foreach (DataGridViewRow row in dtgTitulo.Rows)
{
if (row.Cells["Seleccione"].Value != null && row.Cells["Seleccione"].Value.Equals(true))//Columna de checks
{
contador++;
if (contador <= 0)
{
btnUno.Enabled = false;
btnVarios.Enabled = false;
}
else if (contador == 1)
{
btnUno.Enabled = true;
btnVarios.Enabled = false;
}
else
{
btnUno.Enabled = false;
btnVarios.Enabled = true;
}
}
}
}
Can someone help me? Any suggestion?
UPDATE
HOW TO I LOAD THE DATAGRIDVIEW WITH CHECKBOXES:
private DataTable Query()
{
DataTable datos = new DataTable();
SqlConnection sqlConn = new SqlConnection("STRING");
try
{
sqlConn.Open();
string consulta = "SELECT Titulo AS Título FROM V_CuetaWeb GROUP BY titulo ORDER BY titulo DESC";
SqlCommand sqlCommand = new SqlCommand(consulta, sqlConn);
SqlDataAdapter da = new SqlDataAdapter(sqlCommand);//este se encarga de inicializar el command
da.Fill(datos);
sqlConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return datos;
}
I form_Load:
private void Form1_Load(object sender, EventArgs e)
{
ds = new DataSet();
ds.Tables.Add(Query());
ds.Tables[0].Columns.Add("Seleccione", typeof(bool));
dtgTitulo.DataSource = ds.Tables[0];
}
Try Below code:
AS per #JIMI's suggestion
private void dtgTitulo_CellMouseUp(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex != 1) return;
dtgTitulo.CommitEdit(DataGridViewDataErrorContexts.Commit);
var contador = dtgTitulo.Rows.OfType<DataGridViewRow>().Count(r => (r.Cells[1].Value != null) && ((bool)r.Cells[1].Value == true));
if (contador <= 0)
{
btnUno.Enabled = false;
btnVarios.Enabled = false;
}
else
{
if (contador == 1)
{
btnUno.Enabled = true;
btnVarios.Enabled = false;
}
else
{
btnUno.Enabled = false;
btnVarios.Enabled = true;
}
}
}
after click on checkboxes they show/hide ticks, but value in cell doesn't change immediately. call EndEdit to apply them.
private void dtgTitulo_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || dtgTitulo.Columns[e.ColumnIndex].Name != "Seleccione")
return;
dtgTitulo.EndEdit();
int contador = 0;
foreach (DataGridViewRow row in dtgTitulo.Rows)
{
if (Equals(true, row.Cells["Seleccione"].Value))
{
contador++;
if (contador > 1)
break;
}
}
btnUno.Enabled = contador == 1;
btnVarios.Enabled = contador > 1;
}
p.s. note optimizations made to avoid unnecessary iterations
Related
I am developing a project. In this project, the rows I selected from datagridview1 should be added to the child table and deleted from there. Later, I want to be able to add the rows that I don't want to pull from datagridview2 back to datagridview1. How do I do this?
Here is my codes:
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM AçıkKalemler", con);
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = false; // Select butonlarının seçili olmadan gelmesini sağlar.
dataGridView1.Rows[n].Cells[1].Value = item["MÜŞTERİ"].ToString();
dataGridView1.Rows[n].Cells[2].Value = item["SIPARISNUMARASI"].ToString();
dataGridView1.Rows[n].Cells[3].Value = item["SATISNUMARASI"].ToString();
dataGridView1.Rows[n].Cells[4].Value = item["KALEMTANIMI"].ToString();
dataGridView1.Rows[n].Cells[5].Value = item["PLANLANANTESLİMTARİHİ"].ToString();
dataGridView1.Rows[n].Cells[6].Value = item["SIPARISMIKTARI"].ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = false;
dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
dataGridView2.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
dataGridView2.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
dataGridView2.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
dataGridView2.Rows[n].Cells[6].Value = item.Cells[6].Value.ToString();
}
private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
if ((bool)dataGridView1.SelectedRows[0].Cells[0].Value == false)
{
dataGridView1.SelectedRows[0].Cells[0].Value = true;
}
else
{
dataGridView1.SelectedRows[0].Cells[0].Value = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView2.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = false;
dataGridView1.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
dataGridView1.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
dataGridView1.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
dataGridView1.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
dataGridView1.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
}
}
}
private void dataGridView2_MouseClick(object sender, MouseEventArgs e)
{
if ((bool)dataGridView2.SelectedRows[0].Cells[0].Value == false)
{
dataGridView2.SelectedRows[0].Cells[0].Value = true;
}
else
{
dataGridView2.SelectedRows[0].Cells[0].Value = false;
}
}
Button3 should do this.
Please help me!!
i have the following Problem. I have a DatagridView with ComboBoxColumns. When i change the first ComboBox the second will be filled with data and when i select the first two the third will be filled.
It's working fine until here. My Problem is i have an add Button for new Rows and when i select the first ComboBoxColumn on the new (second) Row it will trigger also the values on the first Row and Update the second ComboBoxColumn on that row, but i only want to change the Values in a row not on all Rows.
Does someone have an Idea?
I tried to save the row number from where the Change came from, but i didn't affect anything.
Here's what i have so far:
private String id;
private int row_number;
//Fill first Combo
private void fill_first_combo()
{
datagridview_col1.Items.Clear();
if (datagridview.SelectedRows.Count > 0)
{
string rcs = db_conn.connection();
using (var OraConn = new OracleConnection(rcs))
{
using (var OraCmd = OraConn.CreateCommand())
{
try
{
OraConn.Open();
OraCmd.BindByName = true;
OraCmd.CommandText = "Oracle Command"
OracleDataReader OraDataReader = OraCmd.ExecuteReader();
if (OraDataReader.Read() == false)
{
//MessageBox
}
else
{
using (var OraDat = new OracleDataAdapter(OraCmd))
{
using (var table = new DataTable())
{
OraDat.Fill(table);
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
if (row[column] != null)
{
if (column.ColumnName == "COLUMNNAME")
{
datagridview_col1.Items.Add(row[column.ColumnName].ToString());
id = row[column.ColumnName].ToString().Substring(0, 6);
}
}
}
}
}
}
}
}
catch (OracleException ex)
{
//Exceptions
}
finally
{
OraConn.Dispose();
}
}
}
}
else
{
//MessageBox
}
}
//Fill 2nd ComboBoxColumn
private void fill_combobox2(int row_number)
{
datagridview_col2.Items.Clear();
string rcs = db_conn.connection();
using (var OraConn = new OracleConnection(rcs))
{
using (var OraCmd = OraConn.CreateCommand())
{
try
{
OraConn.Open();
OraCmd.BindByName = true;
OraCmd.CommandText = "Oracle Command with id as a Parameter";
var id_param = new OracleParameter("id", id);
OraCmd.Parameters.Add(id_param);
OracleDataReader OraDataReader = OraCmd.ExecuteReader();
if (OraDataReader.Read() == false)
{
//MessageBox
}
else
{
using (var OraDat = new OracleDataAdapter(OraCmd))
{
using (var combo2_table = new DataTable())
{
OraDat.Fill(combo2_table);
foreach (DataRow row in combo2_table.Rows)
{
foreach (DataColumn column in combo2_table.Columns)
{
if (row[column] != null)
{
if (column.ColumnName == "BUILDING_LESS")
{
datagridview_col2.Items.Add(row[column.ColumnName].ToString());
}
}
}
}
}
}
}
}
catch (OracleException ex)
{
//Catch Exceptions
}
finally
{
OraConn.Dispose();
}
}
}
}
//Trigger SelectionChange
private void datagridview_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
cb.SelectedIndexChanged -= new EventHandler(selectionchange);
cb.SelectedIndexChanged += selectionchange;
}
}
private void selectionchange(object sender, EventArgs e)
{
try
{
//ComboBox cb = (ComboBox)sender;
String selected = (sender as ComboBox).SelectedItem.ToString();
if (datagridview.CurrentCell.ColumnIndex == 0)
{
row_number = datagridview.CurrentCell.RowIndex;
id = selected.Substring(0, 6);
if (!String.IsNullOrEmpty(id))
{
fill_combobox2(row_number);
}
else if (String.IsNullOrEmpty(id))
{
//MessageBox);
}
}
else if (datagridview.CurrentCell.ColumnIndex == 1)
{
section = selected.Substring(0, 2);
if (!String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(value2))
{
//MessageBox
}
else if (String.IsNullOrEmpty(id) && !String.IsNullOrEmpty(value2))
{
//MessageBox
}
else if (String.IsNullOrEmpty(id) && String.IsNullOrEmpty(value2))
{
//MessageBox
}
}
}
catch (Exception ex)
{
//MessageBox
}
}
have you try using CellValueChange event to control this? Then you can do something like
The code is in VB but you may convert to C# using online tool
Try
Dim _ColumnIndex As Integer = datagridview.Columns("Combo1").Index
Dim _ColumnIndex2 As Integer = datagridview.Columns("Combo2").Index
If e.ColumnIndex = _ColumnIndex Then
'----your formula----
End If
Catch ex As Exception
End Try
I am selecting a row from Gridview, working good except for checkbox, like I am assigning value of checkbox retreived from gridview to checkbox that is placed on web form but it isn't represented by checkbox on form, it shows empty checkbox in every case
if (gridviewDesignations.SelectedRow.Cells[5].Text == " ")
{
chkIsHead.Text = gridviewDesignations.SelectedRow.Cells[5].Text;
}
in short, checkbox is not picking value from gridview
Update:
tried this too:
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
Update:
my full code:
public partial class frmDesignations : System.Web.UI.Page
{
AccessibleVariables accessVariables = new AccessibleVariables(); //Used to access global variables
public void Clear(params TextBox[] txtBoxes)
{
foreach (TextBox txtbx in txtBoxes)
{
txtbx.Text = "";
}
}
public void fillddlDepartments()
{
ManageDepartmentsBizz mngDepBizz = new ManageDepartmentsBizz();
DataSet ds = (DataSet)mngDepBizz.SelectDepartments();
if (ds.Tables[0].Rows.Count != 0)
{
ddlDepartments.DataValueField = "DepID";
ddlDepartments.DataTextField = "DepName";
ddlDepartments.DataSource = ds.Tables[0];
// ddlDepartments.SelectedIndex = -1;
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, "--Select--");
}
//else
// ddlDepartments.SelectedIndex = -1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
if (!IsPostBack)
{
fillddlDepartments();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(-1, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead);
//-1 is bogus,used to fill parameters criteria i.e no of params
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Insert(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Saved";
HiddenFieldShowMessage.Value = "True";
Clear(txtTitle, txtSelectedID, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "RecordAlreadyExists";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotSaved";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnSearchPopup_Click(object sender, EventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepsBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepsBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
lblMsgPopUp.Visible = false;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
else
{
lblMsgPopUp.Visible = true;
gridviewDesignations.Visible = false;
}
}
protected void gridviewDesignations_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
gridviewDesignations.PageIndex = e.NewPageIndex;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (gridviewDesignations.SelectedRow != null)
{
if (gridviewDesignations.SelectedRow.Cells[1].Text == " ")
{
txtSelectedID.Text = string.Empty;
}
else
{
txtSelectedID.Text = gridviewDesignations.SelectedRow.Cells[1].Text;
}
if (gridviewDesignations.SelectedRow.Cells[2].Text == " ")
{
txtTitle.Text = string.Empty;
}
else
{
txtTitle.Text = gridviewDesignations.SelectedRow.Cells[2].Text;
}
if (gridviewDesignations.SelectedRow.Cells[3].Text == " ")
{
ddlDepartments.SelectedValue = string.Empty;
}
else
{
ddlDepartments.SelectedValue = gridviewDesignations.SelectedRow.Cells[3].Text;
accessVariables.DepID = Convert.ToInt32(gridviewDesignations.SelectedRow.Cells[3].Text);
ViewState["depID"] = accessVariables.DepID;
}
if (gridviewDesignations.SelectedRow.Cells[4].Text == " ")
{
txtContactNo.Text = string.Empty;
}
else
{
txtContactNo.Text = gridviewDesignations.SelectedRow.Cells[4].Text;
}
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
gridviewDesignations.DataBind();
gridviewDesignations.SelectedIndex = -1;
HiddenFieldShowHideButtons.Value = "True";
}
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(txtSelectedID.Text);
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(id, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead );
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Update(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtSelectedID, txtTitle, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnDeletePopUp_Click(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(txtSelectedID.Text.Trim());
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
mngDepBizz.Delete(ID);
Clear(txtTitle, txtSelectedID, txtContactNo);
HiddenFieldSetMessage.Value = "Deleted";
HiddenFieldShowMessage.Value = "True";
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotDeleted";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnClosePopup_Click(object sender, EventArgs e)
{
Clear(txtTitle, txtSelectedID, txtContactNo);
}
protected void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
else
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
}
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
}
I believe the following is what you need to do:
Then select EditProgrammatically.
I'm not sure if yoou'll need to manually put data into the grid though but that won't be too hard. Examples can be seen here : http://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
PS : You can set the DataSource in the grid view to the DataTable.
I am working in Window application in asp.net. I have a GUI in which user enter a product name and quantity in text boxes. On Add button click i am adding a new row in Datagridview and set the value of productname and quantity in datagridview columns. I am not inserting record in Database and I am only save record in Datatable as well add record in Datagridview.
Problem is that when I select a last row from datagridview and press delete button from keyboard then it generate an error
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
static public DataTable gdt;
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtItemCode.Text.Trim() == "")
{
MessageBox.Show("Enter Item Code");
txtItemCode.Focus();
return;
}
if (txtQty.Text.Trim() == "")
{
MessageBox.Show("Enter Qty");
txtQty.Focus();
return;
}
if (Convert.ToInt32(txtQty.Text.Trim()) <= 0)
{
MessageBox.Show("Qty must be greater than 0");
txtQty.Focus();
return;
}
if (btnAdd.Text == "ADD")
{
DataRow[] dr = gdt.Select("Item_Code = '" + txtItemCode.Text.Trim() + "'");
if (dr.Length > 0)
{
MessageBox.Show("Item Code Already Exist.");
txtItemCode.Text = "";
txtItemCode.Focus();
return;
}
tblItemMasterBLL oItem = new tblItemMasterBLL();
int ItemID = 0;
DataTable dt = new DataTable();
dt = oItem.getItemDetailByItemCode(txtItemCode.Text.Trim());
if (dt.Rows.Count > 0)
{
ItemID = Convert.ToInt32(dt.Rows[0]["Item_ID"]);
gdt.Rows.Add();
gdt.Rows[gdt.Rows.Count - 1]["Item_Code"] = txtItemCode.Text.Trim();
gdt.Rows[gdt.Rows.Count - 1]["Item_ID"] = ItemID;
gdt.Rows[gdt.Rows.Count - 1]["Qty"] = txtQty.Text.Trim();
gdt.Rows[gdt.Rows.Count - 1]["Article_Desc"] = Convert.ToString(dt.Rows[0]["Article_Desc"]);
gdt.Rows[gdt.Rows.Count - 1]["Color_Desc"] = Convert.ToString(dt.Rows[0]["Color_Desc"]);
gdt.Rows[gdt.Rows.Count - 1]["Size_Desc"] = Convert.ToString(dt.Rows[0]["Size_Desc"]);
gdt.Rows[gdt.Rows.Count - 1]["MRP"] = Convert.ToString(dt.Rows[0]["MRP"]);
dgv_Items.DataSource = null;
dgv_Items.DataSource = gdt;
}
else
{
MessageBox.Show("Invalid Item Code");
}
txtItemCode.Text = "";
txtQty.Text = "";
}
else if (btnAdd.Text == "UPDATE")
{
if (gdt.Rows.Count > 0)
{
gdt.Rows[Convert.ToInt32(lblhdnRowIndex.Text)]["Qty"] = txtQty.Text.Trim();
dgv_Items.Rows[Convert.ToInt32(lblhdnRowIndex.Text)].Cells["Qty"].Value = txtQty.Text.Trim();
}
txtItemCode.ReadOnly = false;
txtItemCode.Text = "";
txtQty.Text = "";
lblhdnItemID.Text = "";
lblhdnItemCode.Text = "";
lblhdnQty.Text = "";
btnAdd.Text = "ADD";
lblhdnRowIndex.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dgv_Items_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
try
{
if (MessageBox.Show("Do you want to delete the current row?", "Confirm deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ScrollPosition = 0;
ScrollPosition = dgv_Items.FirstDisplayedScrollingRowIndex;
int iIndex = dgv_Items.CurrentRow.Index;
gdt.Rows.RemoveAt(iIndex);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dgv_Items_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
{
try
{
dgv_Items.DataSource = null;
dgv_Items.DataSource = gdt;
dgv_Items.Rows[dgv_Items.Rows.Count - 1].Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How about ..
ScrollPosition = 0;
dgv_Items.FirstDisplayedScrollingRowIndex=ScrollPosition;
int iIndex = dgv_Items.CurrentRow.Index;
gdt.Rows.RemoveAt(iIndex);
thanks all of u participate to solve my problem. Actually this is index problem.
I have find out the solution In which I have done changes in UserDeletingRow event of Datagridview. I have added a new line in UserDeletingRow eventhich is in bold font. Now my code is working fine.
private void dgv_Items_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
try
{
if (MessageBox.Show("Do you want to delete the current row?", "Confirm deletion",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
ScrollPosition = 0;
ScrollPosition = dgv_Items.FirstDisplayedScrollingRowIndex;
int iIndex = dgv_Items.CurrentRow.Index;
DataRow dr = gdt.Rows[iIndex]; //new added code
gdt.Rows.RemoveAt(iIndex);
gdt.Rows.InsertAt(dr, iIndex); //new added code
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
\mycode
protected void btnRemove_Click(object sender, EventArgs e)
{
try
{
Button lbl = (Button)sender;
GridViewRow gv = (GridViewRow)lbl.NamingContainer;
int rowID = gv.RowIndex - 1;
if (ViewState["dt"] != null)
{
DataTable dt = (DataTable)ViewState["dt"];
// if (dt.Rows.Count > 1)
//{
//Remove the Selected Row data
dt.Rows.Remove(dt.Rows[gv.RowIndex]);
// }
//Store the current data
ViewState["dt"] = dt;
//Re bind the GridView for the updated data
gridIP.DataSource = dt;
gridIP.DataBind();
hdnCount.Value = gridIP.Rows.Count.ToString();
HidingRowID();
if (gridIP.Rows.Count == 0)
{
ReqFromIP.Enabled = true;
ValreqFromIP.Enabled = true;
ReqToIP.Enabled = true;
ValreqToIP.Enabled = true;
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + "Plese specify at least one IP Range." + "');", true);
}
else
{
ReqFromIP.IsValid = true;
ReqFromIP.Enabled = false;
ValreqFromIP.Enabled = false;
ReqToIP.IsValid = true;
ReqToIP.Enabled = false;
ValreqToIP.Enabled = false;
}
}
}
catch (Exception ex)
{
Logging.LogExeption(ex);
}
}
protected void gridIP_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridIP.PageIndex = e.NewPageIndex;
gridIP.DataSource = (DataTable)ViewState["dt"];
gridIP.DataBind();
}