i am using telerik control(data grid view) in my project. but when i want to add new row in data grid, the text of previous rows (bindingSourceService.DataSource = dtservice , bindingSourceUnit.DataSource = dtunit) disappear.
my datagridview has 3 combobox column.
what is wrong? please help me.
my codes:
public void FactorLoad(object sender, EventArgs e)
{
try
{
var cb = new CategoriBll();
DataTable dtcategori = cb.GetAllDataCategori();
bindingSourceCategouri.DataSource = dtcategori;
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
private void DataGridViewFactorCellValueChanged(object sender, GridViewCellEventArgs e)
{
try
{
var row = DataGridViewFactor.CurrentRow;
if ((row != null) && (row.Cells[0].IsCurrent))
{
var categoryId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[0].Value);
var sb = new CategoriOptionBll();
DataTable dtservice = sb.ServiceGetById(categoryId);
bindingSourceService.DataSource = dtservice;
}
if ((row != null) && (row.Cells[1].IsCurrent))
{
var serviceId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[1].Value);
var cbi = new CostBll();
var dtunit = cbi.CostById(serviceId);
bindingSourceUnit.DataSource = dtunit;
}
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
private void DataGridViewFactorCellEditorInitialized(object sender, GridViewCellEventArgs e)
{
try
{
var row = DataGridViewFactor.CurrentRow;
if ((row != null) && (row.Cells[0].IsCurrent))
{
var categoryId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[0].Value);
var sb = new CategoriOptionBll();
DataTable dtservice = sb.ServiceGetById(categoryId);
bindingSourceService.DataSource = dtservice;
}
if ((row != null) && (row.Cells[1].IsCurrent))
{
var serviceId = Convert.ToInt32(DataGridViewFactor.CurrentRow.Cells[1].Value);
var cbi = new CostBll();
var dtunit = cbi.CostById(serviceId);
bindingSourceUnit.DataSource = dtunit;
}
}
catch (Exception ex)
{
ExceptionkeeperBll.LogFileWrite(ex);
}
}
It will disappear because there will be only 1 value in the data source. Try adding value to the data source rather then assigning single value.
Related
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
The program i have create for "Inventory system". And also i have create GridControl from Devexpress Tools. how do i convert this code to Devexpress gridcontrol..
please refer attached image GridControl
private void dgvinvoicesummary_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
int id = e.RowIndex;
DataGridViewRow row = dgvinvoicesummary.Rows[id];
int ddl1 = Convert.ToInt32(row.Cells[2].Value.ToString());
if (dgvinvoicesummary.Columns[e.ColumnIndex].Name == "Update")
{
invoiceSummary Obj = new invoiceSummary
{
CustomerName = row.Cells["customerName"].Value.ToString(),
InvoiceID = Convert.ToInt32(row.Cells["invoiceId"].Value.ToString()),
IssueDate = row.Cells["issue_date"].Value.ToString(),
DueDate = row.Cells["due_date"].Value.ToString(),
Status = row.Cells["Status"].Value.ToString()
};
frmAddinvoice fm = new frmAddinvoice(Obj);
fm.ShowDialog();
this.Close();
GetInvoiceSummaryData();
}
if (dgvinvoicesummary.Columns[e.ColumnIndex].Name == "delete")
{
DeleteInvoiceSummaryRow(ddl1);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The Answer should be like this
private void gridView1_RowCellClick(object sender, RowCellClickEventArgs e)
{
int id = e.RowHandle;
DataRow row = gridView1.GetDataRow(id);
int ddl1 = Convert.ToInt32(gridView1.GetRowCellValue(id, "invoiceId").ToString());
if (e.Column.Name=="ActionUpdate")
{
invoiceSummary Obj = new invoiceSummary
{
CustomerName = gridView1.GetRowCellValue(id, "customerName").ToString(),
InvoiceID = Convert.ToInt32(gridView1.GetRowCellValue(id,"invoiceId").ToString()),
IssueDate = gridView1.GetRowCellValue(id,"issue_date").ToString(),
DueDate = gridView1.GetRowCellValue(id,"due_date").ToString(),
Status = gridView1.GetRowCellValue(id,"Status").ToString(),
PrivateNote = gridView1.GetRowCellValue(id,"privateNotes").ToString(),
PadiAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Amount_Paid").ToString()),
Balance = Convert.ToDouble(gridView1.GetRowCellValue(id,"Balance").ToString()),
PaymentType = gridView1.GetRowCellValue(id,"paymentType").ToString(),
DateOfPayment = gridView1.GetRowCellValue(id,"DateOfPayment").ToString(),
TotalDiscount = Convert.ToDouble(gridView1.GetRowCellValue(id,"TotalDiscount").ToString()),
PackagingAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"PackagingAmount").ToString()),
CustomerNote = gridView1.GetRowCellValue(id,"CustomerNote").ToString(),
TaxTotalAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Tax_Amount").ToString()),
Valuedata = Convert.ToDouble(gridView1.GetRowCellValue(id,"Amount").ToString()),
TotalSubAmount = Convert.ToDouble(gridView1.GetRowCellValue(id,"Total_Amount").ToString()),
};
frmAddinvoice fm = new frmAddinvoice(Obj);
fm.ShowDialog();
this.Close();
GetInvoiceSummaryData();
}
else
{
MessageBox.Show("");
}
}
Im facing a very weird issue, wich should be very simple.
What im trying to achieve: I have 2 datagrids: 1 with invoiceheaders and 1 with invoiceDetails.
When i click on a particular row from the invoiceheaders, the invoicedetails need to change and show the particular details of that invoice. The event im using for this is dgvInvoiceHeaders_SelectionChanged.
So the code in the view:
private void InvoiceListView_Load(object sender, EventArgs e)
{
int invoiceId = 1;
invoiceHeadersBinding.DataSource = invoiceListPresenter.getInvoiceHeaders();
dgvInvoiceHeaders.DataSource = invoiceHeadersBinding;
setInvoiceHeaderColumns();
if (dgvInvoiceHeaders.CurrentRow != null)
{
Int32.TryParse(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString(), out invoiceId);
}
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(invoiceId);
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
private void dgvInvoiceHeaders_SelectionChanged(object sender, EventArgs e)
{
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(Convert.ToInt32(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString()));
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
And this is the code of the methods im calling:
public List<tbl_invoices> invoiceHeaders;
public BindingList<tbl_invoices> getInvoiceHeaders()
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoice = from i in invoices.tbl_invoices
select i;
invoiceHeaders = invoice.ToList();
var listBinding = new BindingList<tbl_invoices>(invoiceHeaders);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
public List<tbl_invoiceDetail> invoiceDetails;
public BindingList<tbl_invoiceDetail> getSelectedInvoiceDetails(int invoiceID)
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoiceDetail = from i in invoices.tbl_invoiceDetail
where i.InvoiceID == invoiceID
select i;
invoiceDetails = invoiceDetail.ToList();
var listBinding = new BindingList<tbl_invoiceDetail>(invoiceDetails);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
But with this example the formload is loaded correctly. But after the event is fired, my invoiceheader datagrid is empty. When i put the text in comment at the method dgvInvoiceHeaders_selectionChanged(), I see that both of the datagrids are filled correctly.
A push in the right direction would be very kind.
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);
}
}