Sorting Gridview breaks ModalPopUp in GridView - c#

I have a gridview that has linkbuttons that call modalpopups and textboxes with values. I am trying to implement sorting for the gridview, but the if(!ispostback) statement I need for sorting prevents the modalpopup from appearing. It also does not sort the textboxes in the gridview. Is there a way to implement sorting without using ispostback in the page_load?
Here is the code for the modalpopup, gridview binding and sorting.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["sortOrder"] = "";
Bind_Gridview("", "");
loadModals();
}
}
protected void viewModal(object sender, EventArgs e)
{
...
mainPanel.Controls.Add(exstModal);
mainPanel.Controls.Add(exstModalBox);
exstModalBox.Show();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
Bind_Gridview(e.SortExpression, sortOrder);
}
public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "desc")
{
ViewState["sortOrder"] = "asc";
}
else
{
ViewState["sortOrder"] = "desc";
}
return ViewState["sortOrder"].ToString();
}
set
{
ViewState["sortOrder"] = value;
}
}
protected void gv1_RowCommand(object sender, GridViewRowEventArgs e)
{
...
CheckBox cb = new CheckBox();
TextBox ca = new TextBox();
ca.Width = 20;
TextBox cga = new TextBox();
cga.Width = 20;
if (e.Row.RowType == DataControlRowType.DataRow) //Foreach row in gridview
{
while (dr1.Read())
{
ca.Text = dr1["cyla"].ToString();
cga.Text = dr1["cga"].ToString();
checkText = dr1["completed"].ToString();
if (checkText == "True")
{
cb.Checked = true;
}
else
{
cb.Checked = false;
}
}
...
dr1.Close();
conn1.Close();
e.Row.Cells[6].Controls.Add(ca);
e.Row.Cells[8].Controls.Add(cga);
e.Row.Cells[9].Controls.Add(cb);
...
}

A GridView has built-in sorting capabilities. Depending on the dataset you are using to populate the data, you likely don't need to manually handle anything manually, let alone with the ViewState.
Check out the second example on this MSDN page and note that it never does anything manually with the ViewState... the OnSorting and OnSorted events are there just to display extra information or to impose requirements:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
If you post a bit more of your code (including your .aspx pages, the markup for the modal popups, and the code for the loadModals() function, we might be able to better help you.

Related

How to change datagridview colors based on value contained within cells

Hi all I would like to change cell index based on certain value like shown below ,I have seen many articles in here, but in ASP.NET this is a windows app how can I archive this thanks with a windows desktop app.Please Note the column that I want indexes changed is created dynamically.Thanks
Dynamic column code creation
private void button3_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
adap.Fill(table);
dataGridView1.DataSource = table;
table.Columns.Add("RESULTS").Expression = "Iif(((ActualWeight >= (.96 * TargetWeight)) And (ActualWeight <= (1.04 * TargetWeight))),'GOOD''BAD'))
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[7].Value.ToString() == "BAD")
row.Cells[7].Style.ForeColor = Color.Red;
//row.Cells["RESULTS"].Style.ForeColor = Color.Red;
}
}
As you are adding a new column to the datatable table, you need to bind the table to the datagridview (refer this : how to bind datatable to datagridview in c#) and then try to change the color.
Try this
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red; //change the color to what you need
}
UPDATE : To iterate through the DataGridView and check for cell contents in a specific column, you need something like
foreach(DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[7].Value.ToString() == "BAD")
row.Cells[7].Style.ForeColor = Color.Red;
//row.Cells["RESULTS"].Style.ForeColor = Color.Red;
}
You need to place this piece of code inside an event that is triggered or function that is called after the DataGridView is populated with data.
Here is some sample code demonstrating the desired result
ASPX:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="true">
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList al = new ArrayList();
al.Add("open"); al.Add("close"); al.Add("other"); al.Add("open"); al.Add("other"); al.Add("close"); al.Add("open");
this.GridView1.DataSource = al;
this.GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[0].Text == "open")
{
e.Row.Cells[0].ForeColor = System.Drawing.Color.Red;
}
else if (e.Row.Cells[0].Text == "close")
{
e.Row.Cells[0].ForeColor = System.Drawing.Color.Black;
}
else
{
e.Row.Cells[0].ForeColor = System.Drawing.Color.Green;
}
}
}

Getting data from GridView after changing the DataSource

I am trying to add the column names of a gridview to a dropdown list.
The problem is when I change the datasource of the gridview, it returns empty.
I am not sure whether the event is working properly, as it does not work with/without it.
I wanted to use the DataBindComplete event, but I could not see it so I tried DataBound instead.
private void BindTable()
{
if (ddTableSearch.SelectedIndex == 0)
{
tblCustomerTableAdapter customerAdapter = new tblCustomerTableAdapter();
GridView2.DataSource = customerAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 1)
{
tblInvoiceTableAdapter invoiceAdapter = new tblInvoiceTableAdapter();
GridView2.DataSource = invoiceAdapter.GetData();
GridView2.DataBind();
}
else if (ddTableSearch.SelectedIndex == 2)
{
tblEstimateTableAdapter estimateAdapter = new tblEstimateTableAdapter();
GridView2.DataSource = estimateAdapter.GetData();
GridView2.DataBind();
}
}
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
ddColumnSearch.Items.Clear();
for (int i = 0; i < GridView2.Columns.Count; i++)
{
ddColumnSearch.Items.Add(new ListItem(GridView2.Columns[i].ToString()));
}
}
What am I doing wrong?
The databound event runs for each record in the gridview. So one issue is that each time you are clearing out the items you added before. Another issue is that you need to get the data from the EventArgs instead of from the gridview.columns since those are not there until after all the data is bound. I think all you need to do is get the data from the header row:
protected void GridView2_DataBound(object sender, EventArgs e)
{
// Populate dropdown with column names
if(e.Row.RowType != DataControlRowType.Header) return; //only continue if this is hdr row
ddColumnSearch.Items.Clear();
foreach (TableCell cell in e.Row.Cells)
{
ddColumnSearch.Items.Add(new ListItem(cell.Text));
}
}

Gridview always show previous selected row

I am updating gridview after selecting row and then clicking edit which works perfectly but one thing is annoying me that whenever i visit that gridview that it shows that ROW SELECTED and Colored. Why ? i want fresh gridview with no record of previous selected data.
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int ComplainantTypeID = Convert.ToInt32(txtSelectedID.Text.Trim());
ComplainantTypeBizz comBizz = new ComplainantTypeBizz(txtName.Text);
ManageComplainantType mngComplainantType = new ManageComplainantType();
bool Result = mngComplainantType.Update(comBizz, ComplainantTypeID);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtName);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
You have to bind the data to the gridview (GridView.DataBind();) after you edit it in the RowUpdated event and set the GridView.SelectedIndex = -1; after each data bind to unselect any row in your grid.
protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
GridView1.DataBind();
GridView1.SelectedIndex = -1;
}
Hope this helps.

unable to retain the values for dynamic creation of grid rows after print

i have a gridview in which i have created dynamic rows in row created event as shown in below code.
protected void grdPBook_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
strPreviousRowID = DataBinder.Eval(e.Row.Date).ToString()}
grdPBook.ShowFooter = false;
}
}
protected void grdPBook_RowCreated(object sender, GridViewRowEventArgs e)
{
bool IsSubTotalRowNeedToAdd = false;
bool IsGrandTotalRowNeedtoAdd = false;
if (ddlSummary.SelectedValue == "0")
{
if ((strPreviousRowID != string.Empty)(DataBinder.Eval(e.Row.DataItem,Date) != null))
{
if (strPreviousRowID != DataBinder.Eval(e.Row.DataItem, Date).ToString())
{
if (ddlSummary.SelectedValue == "0")
{
IsSubTotalRowNeedToAdd = true;
}
}
}
if (IsSubTotalRowNeedToAdd)
{
// ---code for adding dynamic subtotal row-----
}
}
}
when i print the grid the print dialog opens and after closing the dialog the dynamically generated columns of grid disappers and the grid gets messed up coz i m not able to retain the values for Date(here)on the basis of which the dynamic rowsare generated.
How can i achieve the task.Help me.
protected void grdPBook_RowCreated(object sender, GridViewRowEventArgs e)
{
// your code
if (ddlSummary.SelectedValue == "0")
{
//your code
grdPBook.DataSource = dt;
//here dt is your Data Table object containing all rows.
}
grdPBook.DataBind();
}
Use grdPBook.DataBind(); in every Row operations.

ASPX post back problems with combobox

I've created a simple ASPX page that lists records in a GridView. The records are a list of incidents and one of the columns is the ID of the person who reported the incident.
The initial page shows all records but I would like to provide a filter for the ReportedBy column. I've gotten this working by allowing the user to type in the ReportedByID in a textbox and then clicking on the submit button. This refreshes the page as expected with the filtered view.
The code for this page is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (int.TryParse(txtReportedById.Text, out reportedById) == false)
{
reportedById = 0;
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
To make it more user friendly, I decided to add a dropdown box populated with the ReportedBy names for the user to select which would then be used to filter on upon clicking the submit button. The dropdown box has names as the display items but the values should still be set to the IDs.
The problem I have is that the ID number I get from the dropdown box always comes up as the first element of the list rather than the one the user selected at the time they clicked on the submit button.
The code for this page with this implementation is as follows:
public MyPage()
{
this.Load += new EventHandler(Page_Load);
}
protected void Page_Load(object sender, EventArgs e)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
if (IsPostBack == false)
{
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
int reportedById = 0;
if (combobox.SelectedItem != null)
{
if (int.TryParse(combobox.SelectedItem.Value, out reportedById) == false)
{
reportedById = 0;
}
}
DataAccessObj daObj = new DataAccessObj();
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(reportedById);
IncidentGrid.DataBind();
}
Any help would be gratefully appreciated. TIA
Keep in mind that with WebForms the Page_Load code is executed before the event handler code for the control which created the postback.
You have to populate the list in the section where postbacks flags are checked, just like you do with the grid.
if (IsPostBack == false){
//bind the combobox
}
Otherwise, on a postback, the list will re-populate and the selection will be gone.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataAccessObj daObj = new DataAccessObj();
foreach (ReportedByItem repByItem in daObj.GetAllReportedBy())
{
ListItem listItem = new ListItem(repByItem.Name, repByItem.Id.ToString());
combobox.Items.Add(listItem);
}
IncidentGrid.DataSource = daObj.GetIncidentsByReportedById(0);
IncidentGrid.DataBind();
}
}

Categories

Resources