What I'm trying to do is: I have a datagrid which is populated. The last column is a button and i have a time countdown which then presses a button and populates the datagrid. I then want to loop the datagrid and press the button programmatically (like a .PerformClick()) action.
CellContentClick
private void dgView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (toolStrip.Text != "You are successfully logged in ...") {
Helpers.returnMessage("You are not logged in ... aborting ...");
return;
}
// once found we execute: reportBackFound() and update the database
//Helpers.returnMessage("Clicked programatically!");
var senderGrid = (DataGridView)sender;
string rowId = senderGrid.Rows[e.RowIndex].Cells[0].Value.ToString();
string rowNm = senderGrid.Rows[e.RowIndex].Cells[1].Value.ToString();
string rowUi = senderGrid.Rows[e.RowIndex].Cells[2].Value.ToString();
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
{
try {
XmlDocument doc = new XmlDocument();
doc.Load("https://www.thesite.com/api.php?getApiData=1");
XmlNodeList _nodeList = doc.SelectNodes("/api/apiData");
foreach (XmlNode _node in _nodeList)
{
if (rowNm == _node["apiName"].InnerText)
{
// here we do an http webrequest to the url: _node["apiUrl"].InnerText we look for: zd_show.cgi? in the html
// if we find this it's a success.
var success = _useratorRequester.getReportsPage(_node["apiUrl"].InnerText);
if (success.Contains("zd_show.cgi?"))
{
reportBackFound(int.Parse(rowId), int.Parse(_node["apiId"].InnerText));
updateTheLog(int.Parse(rowId), _node["apiName"].InnerText, int.Parse(rowUi), "success");
} else {
// just update the reports log ...
updateTheLog(int.Parse(rowId), _node["apiName"].InnerText, int.Parse(rowUi), "in-progress");
}
if (chkBoxDebug.Checked)
{
File.AppendAllText("Debug\\userator-social.html", success, Encoding.GetEncoding("windows-1251"));
}
} else {
// there is no project in the userator system ...
}
}
} catch (Exception ex) {
Helpers.returnMessage("API TASKS:\n\n" + ex.ToString());
}
}
}
Timer
private void timerCountDown_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
{
timerCountDown.Stop();
btnParseTasks.PerformClick();
foreach (DataGridViewRow row in dgView.Rows) {
if (row.Cells["col4"].Value.ToString() == "Action") {
// perform click event
dgView_CellContentClick(dgView, new DataGridViewCellEventArgs(0, 0));
}
}
counter = 5;
}
lblCountDown.Text = counter.ToString() + " seconds until next check.";
}
I know I need to launch the event handler:
dgView_CellContentClick(dgView, new DataGridViewCellEventArgs(0, 0));
this line is not correct, I'm not sure what to pass in for DataGridViewCellEventArgs.
Related
Here, I developed WPF application using a OLEDB (Access) database and rdlc report. Here, I have problem in Datagrid. THis application run perfect but when I search any record and it gives me error "Please select the record which you want to print !!!". When I debug this application I know about it . When I search any record that time checkbox value is set automatically false. So that's the problem. So please suggest me what i should do? May i change searching code or not and If i change it then please recommend me any good way. Thanks in Advance. Please see my delete button code because when i click on delete but then after it creates this problems.
Below Code is for Searching ChequeName :-
private void txtChequeName_TextChanged(object sender, TextChangedEventArgs e)
{
System.Windows.Controls.TextBox t = (System.Windows.Controls.TextBox)sender;
string filter = t.Text.ToUpper();
ICollectionView cv = CollectionViewSource.GetDefaultView(dgDataArea.ItemsSource);
if (filter == "")
cv.Filter = null;
else
{
cv.Filter = o =>
{
BankMaster p = o as BankMaster;
//if (t.Name == "txtFirstName")
//return (p.FirstName == filter);
return (p.ChequeName.ToUpper().StartsWith(filter));
};
}
}
This below code is for print data :-
private void ImgPrint_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
List<BankMaster> bmlist = dgDataArea.ItemsSource as List<BankMaster>;
if (bmlist != null)
{
foreach (var item in bmlist)
{
if (item.CheckAll == false)
{
MessageBox.Show("Please select the record which you want to print !!!", "Error In Selecting Record", MessageBoxButton.OK, MessageBoxImage.Error);
break;
}
else
{
ChequePrintReport chreport = new ChequePrintReport();
B_SQUARE_System.Core.Utility.GeneralDeclaration.isGridSelectionChange = true;
chreport.ChequeInfo__OnSaved += adddata_BankInfo_OnSaved;
chreport.isEditMode = true;
chreport.currentSelectedItem = bmlist;
chreport.ShowDialog();
break;
}
}
}
}
private void Imgdelete_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
List<BankMaster> bmlist = dgDataArea.ItemsSource as List<BankMaster>;
String msg = "Are you sure you want to delete selected rows ? ";
int count = 0;
if (bmlist != null)
{
foreach (var item in bmlist)
{
if (item.CheckAll == false)
{
MessageBox.Show("Please select the record which you want to delete !!!", "Error In Selecting Record", MessageBoxButton.OK, MessageBoxImage.Error);
break;
}
else
{
if (MessageBox.Show(msg, "Delete Cheque Data", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
{
foreach (var items in bmlist)
{
if (items.CheckAll == true)
{
bmservices.deleteBankMasterInfo(items.Bank_ID);
count++;
}
}
System.Windows.MessageBox.Show("You deleted " + " " + count + " " + "rows.", "Total Deleted Row", MessageBoxButton.OK, MessageBoxImage.Information);
BankMaster_Loaded(sender, e);
}
break;
}
break;
}
}
Application Output
The problem is with your item.CheckAll condition inside your loops. You should not use the else statement here because all the items are not mostly checked-so the else code will run for some items.
Change the code inside the foreach loops like this:
bool printed = false;
foreach (var item in bmlist)
{
if (item.CheckAll)
{
//Place the Printing code here
printed=true;
}
if (printed == false)
{
//Place the Error message here
}
}
Change the delete code in similar way...
I have a program which basically creates, reads, edits, and delete from a linq database.
It does function well on different rows, however when I select the first row to delete it, it acts as if there is no ROW selected so it returns me a "Select Row" output warning.
In addition when I click modify on the first row, it always edits the row below it only. (The other rows are not affected)
This is the 'event update' code in the class :-
public int UpdateEvent(int selectedRow, string name, DateTime date, string eventType, string eventVenue)
{
EventTicketEntities database = new EventTicketEntities();
Event selected = database.Events.Where(x => x.EventId == selectedRow).FirstOrDefault(); //selected row will give the id of the row
if (selected == null)
{
return -1;
}
else
{
selected.EventName = name;
selected.EventDate = date;
selected.EventType = eventType;
selected.EventVenue = eventVenue;
return database.SaveChanges();
}
}
This is the code of the 'event delete' in the class:-
public int DeleteEvent(int selectedRow)
{
EventTicketEntities database = new EventTicketEntities();
Event eventDelete = database.Events.Where(x => x.EventId == selectedRow).FirstOrDefault();
database.Events.Remove(eventDelete); //We use this method to delete the particular customer
return database.SaveChanges(); //returns the affected rows ....
}
This is the code of the button of the form:-
private void btnModify_Click(object sender, EventArgs e)
{
if (SelectedRow != -1) //if not selected do nothing
{
if (MessageBox.Show("Are you sure?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
{
EventBL eBL = new EventBL();
int result = eBL.UpdateEvent(SelectedRow, eventName.Text, calendar.Value, cmbEventType.SelectedValue.ToString(), cmbEventVenue.SelectedValue.ToString());
MessageBox.Show(result + " rows affected!" + SelectedRow);
dgvEvents.DataSource = eBL.GetEvents();
dgvEvents.Refresh();
}
}
else
{
EventBL eBL = new EventBL();
MessageBox.Show("Select Row first" + SelectedRow);
dgvEvents.DataSource = eBL.GetEvents();
dgvEvents.Refresh();
}
}
This is the code of the delete button:-
private void btnDelete_Click(object sender, EventArgs e)
{
if (SelectedRow != -1) //if not selected do nothing
{
if (MessageBox.Show("Are you sure?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
{
EventBL eBL = new EventBL();
int result = eBL.DeleteEvent(SelectedRow);
MessageBox.Show(result + " rows affected!");
dgvEvents.DataSource = eBL.GetEvents();
SelectedRow = -1;
}
}
else
{
MessageBox.Show("Select Row first");
}
}
And this is the code of the event handler of data grid view:-
private void dgvEvents_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > 0)
{
SelectedRow = int.Parse(dgvEvents[0, e.RowIndex].Value.ToString());
}
}
Your help is much appreciated.
Take care-
HurpaDerpa
by the way، selected will always get a value it can't be null
So the condition
If (selected==null)
Will always be false
Because you assign .firstordefault
I have a gridview which allows you to download the files of the rows you checked. It downloads the files into a .zip file. Everything works fine except for two things:
If I select "check all", it only checks all in the first page of the gridview. If there's enough data to have more than one page, how can I make it so the check-all actually selects ALL?
If I have checked boxes across different pages and I click a button that is supposed to download all the files, it only downloads the files of the page that I'm currently viewing. So if I'm viewing gridview page 2, and I download the checked rows, it will only download the files I have checked in page 2 -- even if I have checked boxes in page 1.
Here's my code:
Checkbox and Gridview:
private void RemoveRowIndex(int index)
{
SelectedShotIndex.Remove(index);
}
private void PersistRowIndex(int index)
{
if (!SelectedShotIndex.Exists(i => i == index))
{
SelectedShotIndex.Add(index);
}
}
private List<Int32> SelectedShotIndex
{
get
{
if (ViewState[SELECTED_SHOT_INDEX] == null)
{
ViewState[SELECTED_SHOT_INDEX] = new List<Int32>();
}
return (List<Int32>)ViewState[SELECTED_SHOT_INDEX];
}
}
private void RePopulateCheckBoxes()
{
foreach (GridViewRow row in gvSearchResultsUserAdmin.Rows)
{
var chkBox = row.FindControl("chkShot") as System.Web.UI.WebControls.CheckBox;
IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
if (SelectedShotIndex != null)
{
if (SelectedShotIndex.Exists(i => i == container.DataItemIndex))
{
chkBox.Checked = true;
}
}
}
}
protected void gvSearchResultsUserAdmin_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSearchResultsUserAdmin.PageIndex = e.NewPageIndex;
if (Session["gvSearchResultsUserAdmin"] != null)
{
gvSearchResultsUserAdmin.DataSource = Session["gvSearchResultsUserAdmin"];
}
else
{
//gvSearchResultsUserAdmin.DataSource = ds;
}
foreach (GridViewRow row in gvSearchResultsUserAdmin.Rows)
{
var chkBox = row.FindControl("chkShot") as System.Web.UI.WebControls.CheckBox;
IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
if (chkBox.Checked)
{
PersistRowIndex(container.DataItemIndex);
}
else
{
RemoveRowIndex(container.DataItemIndex);
}
}
LoadGridView();
//gvSearchResultsUserAdmin.DataBind();
RePopulateCheckBoxes();
}
Select all checkbox:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
try
{
System.Web.UI.WebControls.CheckBox ChkBoxHeader = (System.Web.UI.WebControls.CheckBox)gvSearchResultsUserAdmin.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in gvSearchResultsUserAdmin.Rows)
{
System.Web.UI.WebControls.CheckBox ChkBoxRows = (System.Web.UI.WebControls.CheckBox)row.FindControl("chkShot");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
}
else
{
ChkBoxRows.Checked = false;
}
}
}
catch (Exception)
{
}
}
}
My "Download All" Button:
protected void btnDownloadShots_Click(object sender, EventArgs e)
{
using (ZipFile zip = new ZipFile())
{
try
{
foreach (GridViewRow gvrow in gvSearchResultsUserAdmin.Rows)
{
System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)gvrow.FindControl("chkShot");
if (chk.Checked)
{
SqlCommand objcmd = new SqlCommand();
try
{
filmName = gvrow.Cells[1].Text;
shotNumber = int.Parse(gvrow.Cells[2].Text);
}
catch (Exception ex)
{
}
objcmd.CommandType = CommandType.StoredProcedure;
objcmd.CommandText = "ShotIDfromSearch";
objcmd.Parameters.AddWithValue("#filmName", filmName);
objcmd.Parameters.AddWithValue("#shotNumber", shotNumber);
ds = objdb.getDataSetUsingCmdObj(objcmd);
shotID = ds.Tables[0].Rows[0].Field<int>("ShotID");
FilePath = ReturnFilePath(shotID);
//Response.ForceDownload(FilePath, filmName + " - Shot " + shotNumber.ToString() + ".mp4");
zip.AddFile(FilePath, filmName);
}
}
}
catch (Exception)
{
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=Vertov.zip");
Response.ContentType = "application/zip";
zip.Save(Response.OutputStream);
Response.End();
}
}
The best approach for this is to store it first the details in a cache or other alternative storage (checked data) and from there you can pull out the details from cache perhaps to download the files.
After a long time of search on the web for my problem, i ask the question...
I have a DataGridView whith DataGridViewComboBoxColumn in the 2 first columns.
When I change manually the value of the 1st column of the last row, I add a new blank row after this last row if needed.
When I change manually the value of the second column, I change the type of the next columns (Text or Combo) and fill the DataGridViewComboBoxCell.
These 2 points work perfectly with the EditingControlShowing event whitch fires other events. I use this event whitch is the only one returns a ComboBox as e.Control.
My problem is when I want to programmatically fill the values of col 1 & col 2, the EditingControlShowing event doesn't fire as it should.
I've tried with BeginEdit property, with EditMode=EditProgrammatically property, with no more success.
Here is a part of my code (this not the project but a part of a sample, and I can send more if necessary) :
private void btnFill_Click(object sender, EventArgs e)
{
List<string[]> sFilters = new List<string[]>();
string[] filter1 = { "col3", "NOT IN" };
string[] filter2 = { "col5", "BETWEEN" };
sFilters.Add(filter1);
sFilters.Add(filter2);
iRow = -1;
foreach (var sVar in sFilters)
{
iRow++;
try
{
iCol = 0;
dataGridView1.CurrentCell = dataGridView1.Rows[iRow].Cells[iCol];
dataGridView1.BeginEdit(true);
dataGridView1.CurrentCell.Value = sVar[0];
//dataGridView1.EndEdit();
}
catch (Exception Ex)
{
MessageBox.Show("btnFill_Click - iCol=0 - iRow=" + iRow.ToString() + " :\n\n" + Ex.Message);
}
try
{
iCol = 1;
dataGridView1.CurrentCell = dataGridView1.Rows[iRow].Cells[iCol];
//dataGridView1.BeginEdit(true);
dataGridView1.CurrentCell.Value = sVar[1];
//dataGridView1.EndEdit();
}
catch (Exception Ex)
{
MessageBox.Show("btnFill_Click - iCol=1 - iRow=" + iRow.ToString() + " :\n\n" + Ex.Message);
}
}
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
iCol = ((DataGridView)(sender)).CurrentCell.ColumnIndex;
iRow = ((DataGridView)(sender)).CurrentCell.RowIndex;
if (iCol == 0)
{
try
{
// Déclenchement d'un évènement quand 'cboVar' change
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// first remove event handler to keep from attaching multiple
combo.SelectedIndexChanged -= new EventHandler(dataGridView1_cboVar_SelectedIndexChanged);
// now attach the event handler
combo.SelectedIndexChanged += new EventHandler(dataGridView1_cboVar_SelectedIndexChanged);
}
((DataGridView)sender).ClearSelection();
}
catch (Exception Ex)
{
MessageBox.Show("EditingControlShowing() - Col0 :\n\n" + Ex.Message);
}
}
else if (iCol == 1)
{
try
{
ComboBox combo = e.Control as ComboBox;
if (combo != null)
{
// first remove event handler to keep from attaching multiple
combo.SelectedIndexChanged -= new EventHandler(dataGridView1_cboOpe_SelectedIndexChanged);
// now attach the event handler
combo.SelectedIndexChanged += new EventHandler(dataGridView1_cboOpe_SelectedIndexChanged);
}
}
catch (Exception Ex)
{
MessageBox.Show("EditingControlShowing() - Col1 :\n\n" + Ex.Message);
}
}
}
private void dataGridView1_cboVar_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
comboVar = sender as ComboBox;
if (iCol == 0)
{
if (comboVar.SelectedIndex > 0)
{
if (iRow == dataGridView1.RowCount - 1)
dataGridView1.Rows.Add();
}
comboVar.SelectedIndexChanged -= new EventHandler(dataGridView1_cboVar_SelectedIndexChanged);
}
}
catch (Exception Ex)
{
MessageBox.Show("dataGridView1_cboVar_SelectedIndexChanged() :\n\n" + Ex.Message);
}
}
I hope that I am clear enougth...
Thanks a lot for the help, and sorry for my poor English...
Herve
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);
}
}