How to delete multiple checked items in a ListView? - c#

protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
dt.Rows.RemoveAt(i);
}
}
else
{
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
Here it is deleting one row only. How to delete multiple checked items in listview?

As mentioned by Hans Derks above in comment, you are taking data table from session each time but not actually updating it using Session["CurrentTable"]=dt; like:
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
dt.Rows.RemoveAt(i);
Session["CurrentTable"]=dt;
listview1.DataSource = dt;
listview1.DataBind();
}
}
else
{
}
}
BindDataToGridviewDropdownlist();
}

Refactored version of Pranav's answer:
protected void btndelete_Click(object sender, EventArgs e)
{
// Get the Table from the session.
DataTable dt = (DataTable)Session["CurrentTable"];
// Only actually proceed, if we have a value.
if(dt != null)
{
// Loop through each item.
for (int i = 0; i < listview1.Items.Count - 1; i++)
{
// Find the checkbox to determine if it's checked.
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
// Remove the row at the current index.
dt.rows.RemoveAt(i);
}
}
// Update the session and rebind the data.
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}

This works for me .....
protected void btndelete_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (Session["CurrentTable"] != null)
{
dt = (DataTable)Session["CurrentTable"];
int j = 0;
for (int i = 0; i < listview1.Items.Count; i++)
{
ListViewDataItem items = listview1.Items[i];
CheckBox chkBox = (CheckBox)items.FindControl("chkdel");
if (chkBox.Checked == true)
{
dt.Rows.RemoveAt(j);
dt.AcceptChanges();
}
else
{
j++;
}
}
Session["CurrentTable"] = dt;
listview1.DataSource = dt;
listview1.DataBind();
BindDataToGridviewDropdownlist();
}
}

Related

delete row from datagridview a line is never deleted

I am developing a project where I transfer rows between two datagridvews. I want the rows that I transferred from the upper datagridview to the lower datagridview to be deleted from the upper datagridview. But while some lines are deleted, some are not. I share my codes and images with you.
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();
dataGridView2.Rows[n].Cells[7].Value = item.Cells[7].Value.ToString();
}
}
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
if (!row.IsNewRow)
dataGridView1.Rows.Remove(row);
}
}
And the other transfer codes from datagridview2 to datagridview1
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 = true;
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();
dataGridView1.Rows[n].Cells[6].Value = item.Cells[6].Value.ToString();
dataGridView1.Rows[n].Cells[7].Value = item.Cells[7].Value.ToString();
}
// if (e.KeyData == Keys.Delete)
// {
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
if (dataGridView2.Rows.Count > 0)
{
dataGridView2.Rows.Remove(row);
}
}
// }
}
SelectedRowTotal();
}
Why did you use two loops? try this:
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();
dataGridView2.Rows[n].Cells[7].Value = item.Cells[7].Value.ToString();
dataGridView1.Rows.Remove(item);
dataGridView1.Refresh();
}
}
}
and:
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 = true;
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();
dataGridView1.Rows[n].Cells[6].Value = item.Cells[6].Value.ToString();
dataGridView1.Rows[n].Cells[7].Value = item.Cells[7].Value.ToString();
dataGridView2.Rows.Remove(item);
dataGridView2.Refresh();
}
}
SelectedRowTotal();
}
Try following :
for(int i = dataGridView2.Rows.Count - 1; i >= 0; i--)
{
DataGridViewRow item = dataGridView2.Rows[i];
if ((bool)item.Cells[0].Value == true)
{
dataGridView1.Rows.Add(item);
dataGridView2.Rows.Remove(item);
}
}

ASP.NET - Retrieving Grid View Data when EnableViewState is Set to False

I am building an application that needs to display data in a GridView control, grouped by a particular value, and then export it to PDF.I used this set of classes here (http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm) for grouping, and it works well. However, I had to set EnableViewState to false for it to work properly. The problem comes when I need to export it to PDF. Previously (before using GridViewHelper), this was working. However, it now generates an empty report (I suppose because EnableViewState is false).
How can I save the data and structure of the GridView produced through use of the GridViewHelper class in order to export it to PDF?
Some of my aspx (portions of code omitted for brevity)
public partial class all : System.Web.UI.Page
{
Int32 userID;
Int32 currentID;
protected void Page_Load(object sender, EventArgs e)
{
GridViewHelper helper = new GridViewHelper(allTicketGrid);
helper.RegisterGroup("propName", true, true);
helper.ApplyGroupSort();
userID = Convert.ToInt32(Session["userID"]);
if (Session["userLevel"] == null || Session["userLevel"] == "")
{
Response.Redirect("~/Default.aspx");
}
if (!IsPostBack)
{
this.populate();
}
}
protected void populate()
{
toDateBox.Text = DateTime.Now.ToShortDateString();
fromDateBox.Text = DateTime.Now.ToShortDateString();
using (ticketModel dbContext = new ticketModel())
{
END_USER user = dbContext.END_USER.First(u => u.END_USER_ID == userID);
itemCheckBoxList.DataSource = dbContext.ITEM_TYPE.ToList();
itemCheckBoxList.DataTextField = "DESCRIPTION";
itemCheckBoxList.DataValueField = "ITEM_TYPE_ID";
itemCheckBoxList.DataBind();
List<Int32> propIDList = new List<Int32>();
foreach(END_USER_PROPERTY item in user.END_USER_PROPERTY.ToList() ) {
propIDList.Add((Int32)item.PROPERTY_ID);
}
locationCheckBoxList.DataSource = dbContext.PROPERTies.Where(p=> propIDList.Contains(p.PROPERTY_ID)).ToList();
locationCheckBoxList.DataTextField = "SHORT_NAME";
locationCheckBoxList.DataValueField = "PROPERTY_ID";
locationCheckBoxList.DataBind();
}
}
protected void exportReport(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < allTicketGrid.Columns.Count; i++)
{
dt.Columns.Add(allTicketGrid.Columns[i].HeaderText);
}
foreach (GridViewRow rowView in allTicketGrid.Rows)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < rowView.Cells.Count; i++)
{
dr[i] = rowView.Cells[i].Text.Trim();
}
dt.Rows.Add(dr);
}
Document doc = pdfWorker.readyDocument();
pdfWorker.createTable(doc, dt);
String filePath = Server.MapPath("~/reports/files/");
String fileName = "report_" + DateTime.Now.ToString("MM-dd-yyyy") + ".pdf";
filePath += fileName;
pdfWorker.savePDF(doc, filePath);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.End();
}
protected void generateReport(object sender, EventArgs e)
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
and my pdfWorker class:
static class pdfWorker
{
public static Document readyDocument() {
Document doc = new Document();
Section section = doc.AddSection();
Style docStyles = doc.Styles["Normal"];
docStyles.Document.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Landscape;
docStyles.Font.Size = 8;
docStyles.ParagraphFormat.FirstLineIndent = 0;
return doc;
}
public static void createTable(Document document, DataTable dataTable)
{
Table table = new Table();
table.Format.Font.Size = 6;
table.BottomPadding = 10;
int colCount = dataTable.Columns.Count;
Row pdfRow;
Cell pdfCell;
for (int i = 0; i < colCount; i++)
{
table.AddColumn();
}
pdfRow = table.AddRow();
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.Row.Format.Font.Size = 10;
pdfCell.AddParagraph(dataTable.Columns[i].ToString());
}
foreach (DataRow row in dataTable.Rows)
{
pdfRow = table.AddRow();
pdfRow.HeightRule = RowHeightRule.AtLeast;
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.AddParagraph(row[i].ToString());
}
}
document.LastSection.Add(table);
}
public static void savePDF(Document doc, String fileName) {
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
SaveFileDialog saveDialog = new SaveFileDialog();
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save(fileName);
}
}
}
Thanks so much for any help.
You can put the code that populates the GridView in a separate method:
protected void generateReport(object sender, EventArgs e)
{
BindReportData();
}
private void BindReportData()
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
And call that method at the start of exportReport:
protected void exportReport(object sender, EventArgs e)
{
BindReportData();
...
}

OnSelectedIndexChanged of asp.net DropDownList which is outside datalist

I have a DataList that contains CheckBoxList, and I filter the datalist on selectedindexchanged outside datalist. The problem is when I select value from dropdownlist I can't get the checked values from database
and checkboxlist items count is 0
this is the code
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string GroupValue;
if (DropDownList1.SelectedValue.ToString().IsEmpty()) { GroupValue = null; } else { GroupValue = DropDownList1.SelectedValue.ToString(); }
if (pageMode == PageMode.Update)
{
int rowID = int.Parse(GrdUsers.GetRowValues(GrdUsers.FocusedRowIndex, "ID").ToString());
//ConnectionLayer cn = new ConnectionLayer();
//DataTable dt = cn.ExecutQuery("PagesSys", new object[] { 0, DropDownList1.SelectedItem.Text.ToString() });
//dlstPages.DataSource = dt;
//dlstPages.DataBind();
BindOption(rowID);
}
private void BindOption(int UserID)
{
try
{
if (pageMode == PageMode.Update)
{
if (DropDownList1.SelectedItem.Value != "-1")
{
dlstPages.DataSource = ViewState["FunctionOption"];
dlstPages.DataBind();
if (dlstPages.Items.Count > 0)
{
for (int i = 0; i < dlstPages.Items.Count; i++)
{
DataTable dt = new Users().UserPrivilege(UserID, int.Parse(dlstPages.DataKeys[i].ToString()));
if (dt.Rows.Count > 0)
{
dt.PrimaryKey = new DataColumn[] { dt.Columns["OptionId"] };
CheckBoxList chklist = (CheckBoxList)dlstPages.Items[i].FindControl("chkOption");
for (int j = 0; j < chklist.Items.Count; j++)
{
if (dt.Rows.Find(chklist.Items[j].Value) != null)
{
chklist.Items[j].Selected = true;
}
}
}
}
}
}
}
}
catch (Exception ex)
{
}
}
You need to use the arguments to the function to get the dropdown list object, then you can find the selected value. Something like:
DropDownList ddl= (DropDownList)sender;
var value = ddl.SelectedValue.ToString();

How to read from a GridView

Solution, for at least a specific cell: GridView1.Rows[i].Cells[j].Text;
I've build a simple CSV-Fileupload. After the user uploaded the file he should be able to evaluate the data. When the fileupload was successful the data gets loaded into the GridView1, with this code: (Problem below the code)
string[] readCSV = File.ReadAllLines(lblFilePath.Text);
DataTable dt = new DataTable();
bool bSplitMe = false;
foreach (var rLine in readCSV)
{
if (bSplitMe)
{
string[] aSplittedLine = rLine.Split(";".ToCharArray());
try
{
dt.Rows.Add(aSplittedLine);
}
catch(System.Exception)
{
txtBoxFileOut.Text = rLine;
break;
}
}
else
{
if (rLine.ToLower().StartsWith("definedtestid;"))
{
bSplitMe = true;
string[] aSplittedLine = rLine.Split(";".ToCharArray());
foreach (var rCol in aSplittedLine)
{
dt.Columns.Add(rCol);
}
}
else
{
txtBoxFileOut.Text += rLine.ToString() + "\n";
}
}
}
dt.Columns.Remove("Column1");
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
{
dt.Rows[i][j] = "0";
}
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
After this the user should be able to select a row and display the data from that row in a chart.
Problem: I'm not able to read data from the cells I want, or to read from a "hardcoded" cell.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
GridViewRow row = GridView1.SelectedRow;
txtOutputfield.Text = row.Cells[2].Text;
}
Please check your cell index. Is it correct? For example: the third column will have index "2" not "3"
And, if you use a control to store the data, you need to find that control:
txtOutputfield.Text =
row.Cells[2].FindControl('placeyourcontrolnamehere').Text;
For a specific Cell this worked fine
txtOutputfield.Text = GridView1.Rows[i].Cells[j].Text;

I have added dropdownlist at first row of gridview.Now i want to bind this dropdownlist with some static column

Dropdownlist at first row is empty.i need to add column inside dropdown.here is my code:
private void grdbind()
{
DataTable db = new DataTable();
db = (DataTable)Session["csvdata"];
DataRow newrow = db.NewRow();
db.Rows.InsertAt(newrow, 0);
dgData.DataSource = db;
dgData.DataBind();
}
And this code is use to add dropdown at first position:
protected void dgData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl;
if (e.Row.RowIndex == 0)
{
for (Int32 i = 0; i < e.Row.Cells.Count; i++)
{
ddl = new DropDownList();
ddl.ID = "ddlCol" + i.ToString();
e.Row.Cells[i].Controls.Add(ddl);
}
}
}
Now what i want is to bind this dropdown.??

Categories