Am using vs-2010 with c#, In my application i want to clear a label text in the Page index changing Event. Here is my code
protected void gvDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvDetails.PageIndex = e.NewPageIndex;
// BindGrid(ddlJournal.SelectedItem.Text);
DataSet ds = new DataSet();
ds = ViewState["ds"] as DataSet;
if ((Convert.ToString(ViewState["Template"]) != null
|| (Convert.ToString(ViewState["Template"]) != "")))
{
if ((Convert.ToString(ViewState["Template"]) == "T1"))
{
GridData("T1");
}
else if ((Convert.ToString(ViewState["Template"]) == "T2"))
{
GridData("T2");
}
else if ((Convert.ToString(ViewState["Template"]) == "T3"))
{
GridData("T3");
}
}
else
{
BindGrid(ddlJournal.SelectedItem.Text);
}
btnupdate_Click(sender, e);
lblError.Text = "";
lblSuccess.Text = "";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Key", "call()", true);
}
My problem is the page index are changing properly but the label values do not be empty , what is the problem in my application and how can i fix this.
Thanks in advance .
First of all your code is a mess and do not say thanks here on STACKOVERFLOW and second of all you are calling a method is your gvDetails_PageIndexChanging handler that calls btnupdate_Click(sender, e); do you set a value for your labels there?
Related
I have a method called gridview1_Sorting which works correctly when I click on header in table, but I want to call it automatically after the text inside search box changes and when the table change to the next from paging footer.
I think I should call this method manually from grdView_PageIndexChanging and from the method which detects checkbox state changes:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection(SortDireaction);
firstTable.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
DataView dv = new DataView(firstTable);
GridView1.DataSource = firstTable;
GridView1.DataBind();
SortDireaction = _sortDirection;
int columnIndex = 0;
foreach(DataControlFieldHeaderCell headerCell in GridView1.HeaderRow.Cells)
{
if (headerCell.ContainingField.SortExpression == e.SortExpression)
{
columnIndex = GridView1.HeaderRow.Cells.GetCellIndex(headerCell);
}
}
GridView1.HeaderRow.Cells[columnIndex].Controls.Add(sortImage);
}
Image sortImage = new Image();
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "Asc")
{
_sortDirection = "Desc";
sortImage.ImageUrl = "~/images/u.png";
} else
{
_sortDirection = "Asc";
sortImage.ImageUrl = "~/images/d.png";
}
}
I tried the following two options:
this.GridView1.Sorting +=
new GridViewSortEventHandler(GridView1_Sorting);
and
this.GridView1.Sorting += GridView1_Sorting;
but none seems to work.
I solve d this problem by using gridview1.sort(e.SortExpression,SortDirection.Ascending);
but I think there is another solution by firing gridview.sorting event but I cant do it
I'm validating a DataGridView using the following code ...
void centreDataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (centreDataGridView.Columns[e.ColumnIndex].Name == "code")
{
Regex codeRegex = new Regex("^[0-9]{5}[0-9A-Z]$");
if (!codeRegex.IsMatch(e.FormattedValue.ToString()))
{
centreDataGridView.Rows[e.RowIndex].ErrorText = "error text here";
}
}
}
void centreDataGridView_CellEndEdit(object sender,
DataGridViewCellEventArgs e)
{
centreDataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
}
This works, except that if I enter the new row and then leave it again without entering any data, the error warning icon remains visible in the new row selector. How can I clear it?
Based on the suggestions received so far, I've modified the above code as follows ...
void centreDataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
if (centreDataGridView.Columns[e.ColumnIndex].Name == "code")
{
if (!(centreDataGridView.Rows[e.RowIndex].IsNewRow) ||
(e.FormattedValue.ToString() != string.Empty))
{
Regex codeRegex = new Regex("^[0-9]{5}[0-9A-Z]$");
if (!codeRegex.IsMatch(e.FormattedValue.ToString()))
{
centreDataGridView.Rows[e.RowIndex].ErrorText = "error text here";
}
}
}
}
This does solve the problem of the error indicator displaying beside the new row when no data has been entered. However, when I enter invalid data, in any row, no error indicator is shown when I move off the row for the first time after entering the invalid data. If I move off the row with the invalid data, then move back to it, then move off it again, then the error indicator is shown.
OK I believe I've got it now. I set the ErrorText to an empty string at the start of the CellValidating event handler, instead of in the CellEndEdit event handler, as follows. This is basically a combination of all the suggestions received, so thanks everybody, it was all helpful.
void centreDataGridView_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
centreDataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
if (centreDataGridView.Columns[e.ColumnIndex].Name == "code")
{
if (!(centreDataGridView.Rows[e.RowIndex].IsNewRow) ||
(e.FormattedValue.ToString() != string.Empty))
{
Regex codeRegex = new Regex("^[0-9]{5}[0-9A-Z]$");
if (!codeRegex.IsMatch(e.FormattedValue.ToString()))
{
centreDataGridView.Rows[e.RowIndex].ErrorText = "blah blah blah";
}
}
}
}
Add check if validated row is a NewRow and return if it is.
void centreDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (centreDataGridView.Rows[e.RowIndex].IsNewRow)
{
return; // do not validate row that has no values
}
if (centreDataGridView.Columns[e.ColumnIndex].Name == "code")
{
Regex codeRegex = new Regex("^[0-9]{5}[0-9A-Z]$");
if (!codeRegex.IsMatch(e.FormattedValue.ToString()))
{
centreDataGridView.Rows[e.RowIndex].ErrorText = "error text here";
}
}
}
I am somewhat new to ASP.NET and I am confused by the syntax so I am a little lost. I am trying to hide/disable a button based on an if statement but I dont know how to disable or hide it. I have done C# before but this code looks unfamiliar to me.
Below is some of the code:
C# component:
protected override void Render(HtmlTextWriter writer)
{
string PostCtrl = Request.Params["__EVENTTARGET"];
if (PostCtrl == "AccColLocation_content$collisionLocation$EditColLocation")
{
valDropDownlist(((CustomControl.DropDownValidator)collisionLocation.FindControl("valLoc_municipality")), "CollisionLocation.municipality");
..............
}
}
HTML:
<ItemTemplate>
<asp:LinkButton ID="EditColLocation" runat="server" Text="Edit Collision Location" OnClick="CollisionLocation_Edit" />
</ItemTemplate>
valDropDownList Method:
protected void valDropDownlist(CustomControl.DropDownValidator valDropdown, string DataElement)
{
try
{
bool mvarRequired, srRequired;
DataTable dtDataElement = DBFunctions.DBFunctions.getDataElement(RepDateTime, DataElement);
string s = dtDataElement.Rows[0]["mvarRequired"].ToString();
mvarRequired = (dtDataElement.Rows[0]["mvarRequired"].ToString() == "True") ? true : false;
srRequired = (dtDataElement.Rows[0]["srRequired"].ToString() == "True") ? true : false;
valDropdown.HaveToSelect = (SelfReported) ? srRequired : mvarRequired;
}
catch (Exception err)
{
MessageBox("An error occurred while setting drop down validation rules. " + err.ToString());
}
}
All these buttons are in grid view.
I have something of this nature:
protected void deletedr(object sender, EventArgs e)
{
try
{
GridView gv = (GridView)FindControl("DriverInfo");
gv.DataSource = DBFunctions.DBFunctions.getInfo(ReportID.Value, "", 2); ;
gv.DataBind();
bool isSelectedLast = false;
DataTable dt = DBFunctions.DBFunctions.getInfo(ReportID.Value, "", 2);
if (dlDriverNo.SelectedValue == dt.Rows[dt.Rows.Count - 1]["DriverNo"].ToString())
{
isSelectedLast = true;
}
if (!(DBFunctions.DBFunctions.deleteDriver(ReportID.Value, dlDriverNo.SelectedValue, isSelectedLast)))
{
MessageBox(null);
}
else
{
dlDriverNo.Visible = false;
lblDelDriver.Visible = false;
delDriverconfim.Visible = false;
cancelDel.Visible = false;
dlDriverNo.Items.Clear();
gv.DataSource = DBFunctions.DBFunctions.getInfo(ReportID.Value, "", 2);
gv.DataBind();
}
}
catch (Exception err)
{
MessageBox("An error occurred while deleting the driver. " + err.ToString());
}
}
If your LinkButton is in a GridView, the most interesting problem is getting a handle on it. After you have a handle you can just set it to invisible or disabled:
linkButton.Visible = false;
or
linkButton.Enabled = false;
But to get a handle to the LinkButton control you will need to use .FindControl in a suitable event on the GridView control:
<asp:GridView ID="myGridView" runat="server" OnRowDataBound="myGridView_RowDataBound">
...
</aspGridView>
Then in the code behind you would have:
protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var linkButton = (LinkButton)e.Row.FindControl("EditColLocation");
if (linkButton != null)
{
if (*your condition to check*)
linkButton.Visible = false;
}
}
Hope this will get you moving in the right direction.
you can try
valDropdown.Visible = false; //Mask the control
After the if condition write the below code.
Buttonname.visible=false;
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.
I have one Telerik RadGrid. Using a method I am filling the grid. I have enabled the paging property. I have used ItemTemplate-->ImageButton for delete and edit options. I have set page size as 10. Page load time is working properly and populating the grid. After inserting the 11th row the pagination starts and it will show in the next page with one record. But when I am deleting the 11th row the grid becomes blank. I have used dataset to bind the records.
radgrid.DataBind();
dsDataset.Dispose();
But its item.count is 0. What is the reason?
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
PopulatePackage();
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
protected void gvPackage_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = dsPackage.Tables[0];
dsPackage.Dispose();
//PopulatePackage();
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
private void PopulatePackage()
{
try
{
lblMessage.Text = string.Empty;
SqlHelper objSQL = new SqlHelper();
DataSet dsPackage = new DataSet();
dsPackage = objSQL.ExecuteDataset("AL_PackageType_List_Retrieve", objUtl.NumericEntry(Session["LocationId"].ToString()));
gvPackage.DataSource = null;
gvPackage.DataSource = dsPackage.Tables[0];
gvPackage.DataBind();
//dsPackage.Dispose();
if (gvPackage.Items.Count <= 0)
{
lblMessage.Text = "No Package Details Found...";
gvPackage.Visible = false;
}
else
{
gvPackage.Visible = true;
}
}
catch (Exception ex)
{
lblMessage.Text = objUtl.GetErrorMessage(ex, this);
lblMessage.Visible = true;
}
}
Okay as far as I am understanding it, You have a radgrid in which you have allowed paging and set the page size to 10. Upon inserting the 11th record a new page is shown with that 11th record. And when that 11th record is deleted you are viewing a blank page, instead of showing the page having record from 1 to 10. I hope I am right here.
Anyway. I guess the problem is that the Radgrid is not having the data for the page you are viewing now.
There is an event in RadGrid named NeedDataSource. This Event is fired up whenever the RadGrid needs to display the data. You can call the Binding logic in this event and see if it works for you.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
RadGrid1.DataSource = "BindingSource";
RadGrid1.DataBind();
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
BindGrid();
}
See if this works for you..