I'm new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.
Related
I got an issue with the event-handling in my class:
public partial class BadFiles : Form
{
private DataTable dt = new DataTable();
private string oldCellValue = string.Empty;
public BadFiles()
{
InitializeComponent();
dataGridBadFiles.EditMode = DataGridViewEditMode.EditOnKeystrokeOrF2;
Closing += new CancelEventHandler(BadFiles_Closing);
dataGridBadFiles.CellBeginEdit += new DataGridViewCellCancelEventHandler(BadFiles_CellBeginEdit);
dataGridBadFiles.CellValueChanged += new DataGridViewCellEventHandler(BadFiles_CellValueChanged);
dataGridBadFiles.CellValidating += new DataGridViewCellValidatingEventHandler(BadFiles_CellValidating);
dt.Columns.Add("Files");
for (int i = 0; i < GlobalVars.BadFileNames.Count; i++)
{
dt.Rows.Add(Path.GetFileName(GlobalVars.BadFileNames[i]));
}
dataGridBadFiles.DataSource = dt;
}
private void BadFiles_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
oldCellValue = dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value.ToString();
}
private void BadFiles_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (string.IsNullOrEmpty(e.ToString()) == true || (FileTools.CheckFileName(e.ToString()) == false))
{
e.Cancel = true;
dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value = oldCellValue;
}
}
private void BadFiles_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
var newCellValue = dataGridBadFiles[e.ColumnIndex, e.RowIndex].Value.ToString();
if (FileTools.CheckFileName(newCellValue) == true)
{
var m = new string[]
{
oldCellValue,
newCellValue
};
MessageBox.Show(string.Join(Environment.NewLine, m));
}
else
{
newCellValue = oldCellValue;
MessageBox.Show("Bad Value!");
}
}
private void BadFiles_Closing(object sender, CancelEventArgs e)
{
if(FileTools.CheckFileFolder(GlobalVars.DataInput).Count != 0)
{
e.Cancel = true;
MessageBox.Show("Please rename all files in the list!", "Rename Files", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
The CellValidating event doesn't fire/work, so i tested something else with the CellValueChanged event but that isn't working either. The class shows a Form with a GridView filled from a list with bad filenames. Those filenames must be renamed from the user with a check if the new filenames are OK before changing them. The problem is that the filename checking doesn't work because of the events not firing when supposed to.
I am using grid view check box to select all the values in the grid view when i click the check box, but the problem i am facing is it is selecting the only the first page value how ever i have coded to bring all the values in but in design it is not working out
this is the image
i want all the check box to checked in design when i press the all check button.
protected void gvBatch_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType != DataControlRowType.Header && e.Row.RowType != DataControlRowType.Footer && e.Row.RowType != DataControlRowType.Pager)
{
DropDownList ddlcountry1 = (DropDownList)e.Row.FindControl("ddlcountry");
populateLocationValues(ddlcountry1);
{
ArrayList checkboxvalues = (ArrayList)Session["BP_PrdId"];
//string Bp_Id = "";
if (checkboxvalues != null && checkboxvalues.Count > 0)
{
string strBp_Id = ((HiddenField)e.Row.FindControl("hf_ProductLblId")).Value.ToString();
if (checkboxvalues.Contains(strBp_Id))
{
CheckBox myCheckBox = (CheckBox)e.Row.FindControl("chkPLPSltItem");
myCheckBox.Checked = true;
}
}
}
DataSet dsaccess = MenuRestriction();
DataRow dr = null;
string sView = "";
string sEdit = "";
string sInsert = "";
string sDeactive = "";
if (dsaccess.Tables.Count > 0)
{
if (dsaccess.Tables[0].Rows.Count > 0)
{
dr = dsaccess.Tables[0].Rows[0];
sView = dr["MnuRgts_View"].ToString();
sEdit = dr["MnuRgts_Edit"].ToString();
sInsert = dr["MnuRgts_Insert"].ToString();
sDeactive = dr["MnuRgts_DeActivate"].ToString();
if (sInsert == "Y" && sDeactive == "Y")
{
BtnDelete.Visible = true;
imgNew.Visible = true;
}
else
{
BtnDelete.Visible = false;
imgNew.Visible = false;
if (sInsert == "Y")
{
imgNew.Visible = true;
}
if (sDeactive == "Y")
{
BtnDelete.Visible = true;
}
}
}
}
}
}
catch (Exception ex)
{
log.Error("gvBatch_RowDataBound", ex);
}
}
protected void gvBatch_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
RememberOldValues();
gvBatch.PageIndex = e.NewPageIndex;
//RetrieveValues();
BindGrid();
LoadLocation();
//RePopulateValues();
}
private void RememberOldValues()
{
ArrayList checkboxvalues = new ArrayList();
string strBp_Id = "";
foreach (GridViewRow row in gvBatch.Rows)
{
//index = (int)gvBatch.DataKeys[row.RowIndex].Value;
strBp_Id = ((HiddenField)row.FindControl("hf_ProductLblId")).Value.ToString();
bool result = ((CheckBox)row.FindControl("chkPLPSltItem")).Checked;
// Check in the Session
if (Session["BP_PrdId"] != null)
checkboxvalues = (ArrayList)Session["BP_PrdId"];
if (result)
{
if (!checkboxvalues.Contains(strBp_Id))
checkboxvalues.Add(strBp_Id);
}
else
{
if (checkboxvalues.Contains(strBp_Id))
checkboxvalues.Remove(strBp_Id);
}
}
if (checkboxvalues != null && checkboxvalues.Count > 0)
Session["BP_PrdId"] = checkboxvalues;
}
protected void gvBatch_PreRender(object sender, EventArgs e)
{
try
{
if (gvBatch.TopPagerRow != null)
{
((Label)gvBatch.TopPagerRow.FindControl("lbCurrentPage")).Text = (gvBatch.PageIndex + 1).ToString();
((Label)gvBatch.TopPagerRow.FindControl("lbTotalPages")).Text = gvBatch.PageCount.ToString();
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnFirst")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnPrev")).Visible = gvBatch.PageIndex != 0;
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnNext")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
((LinkButton)gvBatch.TopPagerRow.FindControl("lbtnLast")).Visible = gvBatch.PageCount != (gvBatch.PageIndex + 1);
DropDownList ddlist = (DropDownList)gvBatch.TopPagerRow.FindControl("ddlPageItems");
ddlist.SelectedIndex = ddlist.Items.IndexOf(ddlist.Items.FindByValue(ViewState["DropDownPageItems"].ToString()));
gvBatch.AllowPaging = true;
gvBatch.TopPagerRow.Visible = true;
}
}
catch (Exception ex)
{
}
}
protected void gvBatch_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "EDIT")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
string strAgentName = ((HiddenField)row.FindControl("hf_loginName")).Value.ToString();
if (strAgentName != "")
{
Response.Redirect("CustomerDetails.aspx?Name=" + strAgentName, false);
}
}
}
catch (Exception ex)
{
log.Error("gvAgentRowcommand_AgentSummary", ex);
}
}
You can keep a boolean field in your code and set its value to true whenever the select all is clicked. When loading new pages, you can check that field to automatically display all checked. The same can be done when exporting the grid also.
you can modify and use the following Method
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells["Column_Name"].Value) == false)
{
item.Cells["Column_Name"].Value = true;
}
}
}
the 'Column_name' is the name of the checkbox column. if you haven'nt named it yet you can also use the index number .
in your case its 0
private void selectAllChecksInDAtaGrid()
{
foreach (DataGridViewRow item in myDataGrid.Rows)
{
if (Convert.ToBoolean(item.Cells[0].Value) == false)
{
item.Cells[0].Value = true;
}
}
}
You should update (ArrayList)Session["BP_PrdId"] to include all the "Id"s of datasource of gridview. then bind data again.
I have a field named country in Invoice.aspx form. I have the below code.
invoice.aspx
<asp:DropDownList ID="lstCountryy" runat="server" Width="216px" Height="27px" AutoPostback="false">
</asp:DropDownList>
invoice.aspx.cs
lstCountryy.SelectedValue = dtInquiry.Rows[0]["country"].ToString();
Page load:
protected void Page_Load(object sender, EventArgs e)
{
txtTotal.Attributes.Add("readonly", "readonly");
txtvatt.Attributes.Add("readonly", "readonly");//added by chetan
txtDiscount.Attributes.Add("readonly", "readonly");//added by chetan
txtAmountInWords.Attributes.Add("readonly", "readonly");
if (!IsPostBack)
{
loadInvoiceDetails();
//SetAllCountries();//added by chetan
if (lstCountryy.SelectedValue == "U.A.E" || lstCountryy.SelectedValue == "BAHRAIN" || lstCountryy.SelectedValue == "SAUDI ARABIA")
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "float");
trdeclaration.Visible = false;
//txtvat.Enabled = true;
}
else
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "none");
trdeclaration.Visible = true;
}
}
}
Bind dropdownlist:
protected void SetAllCountries()
{
try
{
string queryStrUserType = "SELECT country_id,country_name FROM crm_countries";
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(queryStrUserType);
lstCountryy.DataSource = dt;
lstCountryy.DataValueField = "country_id";
lstCountryy.DataTextField = "country_name";
lstCountryy.DataBind();
lstCountryy.Items.Insert(0, "--Select--");
}
catch (Exception Ex)
{
}
}
dtInquiry is my Inquiry table in which country field is there and I am fetching the value from inquiry form to invoice form. I am not getting the selected value; it shows blank (""). I don't know what's wrong with that. I am a beginner in C#.
I was not getting the selected value.It should be like this: SetAllCountries Should be first and then loadinvoicedetails.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetAllCountries();
loadInvoiceDetails();
.....
.....
}
}
I want to display data Master/Details stype with DataGrid not GridView or anything else. At the present I must put a dropdownlist to do this manually. So how can do it automatically whenever we click one master item in the Master DataGrid then it link to Details DataGird , like this:
private void BindGridMaster()
{
grdReceivedNote.DataSource = ReceivedNoteService.ReceivedNote_GetByAll();
grdReceivedNote.DataBind();
if (grdReceivedNote.PageCount <= 1)
{
grdReceivedNote.PagerStyle.Visible = false;
}
else
{
grdReceivedNote.PagerStyle.Visible = true;
}
}
private void BindGridDetails()
{
grdReceivedNoteDetails.DataSource = RevNoteDetailsService.RevNoteDetails_GetByAll();
grdReceivedNoteDetails.DataBind();
if (grdReceivedNoteDetails.PageCount <= 1)
{
grdReceivedNoteDetails.PagerStyle.Visible = false;
}
else
{
grdReceivedNoteDetails.PagerStyle.Visible = true;
}
}
protected void grdReceivedNote_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
{
if (itemType == ListItemType.Header)
{
object checkBox = e.Item.FindControl("chkSelectAll");
if ((checkBox != null))
{
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
}
}
else
{
string tableRowId = grdReceivedNote.ClientID + "_row" + e.Item.ItemIndex.ToString();
e.Item.Attributes.Add("id", tableRowId);
object checkBox = e.Item.FindControl("chkSelect");
if ((checkBox != null))
{
e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
}
}
}
}
protected void grdReceivedNoteDetails_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if ((itemType != ListItemType.Footer) && (itemType != ListItemType.Separator))
{
if (itemType == ListItemType.Header)
{
object checkBox = e.Item.FindControl("chkSelectAll");
if ((checkBox != null))
{
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelectAll_OnClick(this)");
}
}
else
{
string tableRowId = grdReceivedNote.ClientID + "_row" + e.Item.ItemIndex.ToString();
e.Item.Attributes.Add("id", tableRowId);
object checkBox = e.Item.FindControl("chkSelect");
if ((checkBox != null))
{
e.Item.Attributes.Add("onMouseMove", "Javascript:chkSelect_OnMouseMove(this)");
e.Item.Attributes.Add("onMouseOut", "Javascript:chkSelect_OnMouseOut(this," + e.Item.ItemIndex.ToString() + ")");
((CheckBox)checkBox).Attributes.Add("onClick", "Javascript:chkSelect_OnClick(this," + e.Item.ItemIndex.ToString() + ")");
}
}
}
}
protected void grdReceivedNote_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdReceivedNote.CurrentPageIndex = e.NewPageIndex;
BindGridMaster();
}
protected void grdReceivedNoteDetails_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
grdReceivedNoteDetails.CurrentPageIndex = e.NewPageIndex;
BindGridMaster();
}
protected void grdReceivedNote_ItemCommand(object source, DataGridCommandEventArgs e)
{
string strCA = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Edit":
Insert = false;
Id = strCA;
ViewCustomers();
ViewRevType();
//ViewRevNote();
//ViewItems();
List<Data.ReceivedNote> listE = ReceivedNoteService.ReceivedNote_GetById(Id);
txtRevNote_No.Text = listE[0].RevNote_No;
txtRevDate.Text = listE[0].RevDate;
txtNotes.Text = listE[0].Notes;
drlCustIdAdd.SelectedValue = listE[0].CustID;
drlRevTypeIdAdd.SelectedValue = listE[0].RevTypeID;
pnViewMaster.Visible = false;
pnUpdateMaster.Visible = true;
break;
case "Delete":
ReceivedNoteService.ReceivedNote_Delete(strCA);
BindGridMaster();
break;
}
}
protected void grdReceivedNoteDetails_ItemCommand(object source, DataGridCommandEventArgs e)
{
string strCA = e.CommandArgument.ToString();
switch (e.CommandName)
{
case "Edit":
Insert = false;
Id = strCA;
//ViewCustomers();
//ViewRevType();
ViewRevNote();
ViewItems();
List<Data.RevNoteDetails> listE = RevNoteDetailsService.RevNoteDetails_GetById(Id);
txtQuantity.Text = listE[0].Quantity;
drlRevNoteIdAdd.SelectedValue = listE[0].RevNoteID;
drlItemIdAdd.SelectedValue = listE[0].ItemID;
pnlViewDetails.Visible = false;
pnlUpdateDetails.Visible = true;
break;
case "Delete":
RevNoteDetailsService.RevNoteDetails_Delete(strCA);
BindGridDetails();
break;
}
}
I'm have problemas to work with Session in my project ASp.NEt c# in IE9.
Sometimes occured error:
"Object reference not set to an instance of as object"
Other problem is that in IE9, sometimes not save my Session to change Idiom to others pages.
In Chrome all works good!
Below is my Page_Load and CarregaGrid(). This problem occured in sometimes, no all time, and in any page no in all page or just in one specific page.
public void CarregaGrid()
{
var listByGroupM = new ManageUsers().ConsultUsersGroupM();
if (listByGroupM != null)
{
this.GridView1.DataSource = listByGroupM;
if (listByGroupM.Count != 0)
{
this.GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
if (divModify.Visible == true)
{
foreach (GridViewRow row in GridView1.Rows)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
if (Session["idioma"].ToString() != null)
{
idioma = Session["idioma"].ToString();
}
Idioma.MudaCultura(idioma);
Button btnDelete = (Button)row.FindControl("btnDelete");
btnDelete.Text = Idioma.RetornaMensagem("btnDelete");
string UserName = row.Cells[1].Text;
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "x.com", "x", "xxx");
UserPrincipal insUserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, UserName);
if (insUserPrincipal == null)
{
row.Cells[2].Text = "";
row.Cells[3].Text = "";
}
else
{
string Email = insUserPrincipal.EmailAddress;
row.Cells[2].Text = Email;
string DisplayName = insUserPrincipal.DisplayName;
row.Cells[3].Text = DisplayName;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
if (Session["idioma"].ToString() != null)
{
idioma = Session["idioma"].ToString();
}
Idioma.MudaCultura(idioma);
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
}
}
protected void pt_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("pt");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "pt";
}
protected void en_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("en");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "en";
}
protected void es_OnChange(object sender, EventArgs e)
{
Idioma.MudaCultura("es");
Label1.Text = Idioma.RetornaMensagem("lblUserAdd");
CarregaGrid();
Session["idioma"] = "es";
}
replace
if (Session["idioma"].ToString() != null)
with
if (Session["idioma"] != null)
If the session object is NULL, then calling .ToString() will throw an error.
Change:
if (Session["idioma"].ToString() != null)
to:
if (Session["idioma"] != null)