ASP.NET C# trying to hide a link button - c#

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;

Related

Adding a dropdown list from server side

i have this following code :
<asp:DropDownList ID="dd_SubCategory" Width="160px" runat="server" DataTextField="CATEGORY_NAME" DataValueField="CATEGORY_ID"></asp:DropDownList>
<br />
<asp:Panel ID="pnl_SubCatg" runat="server"></asp:Panel>
<asp:ImageButton ID="Ib_AddSubCategory" runat="server" OnClick="Ib_AddSubCategory_Click" ImageUrl="/images/add.gif" />
protected void Ib_AddSubCategory_Click(object sender, ImageClickEventArgs e)
{
string SelectedCategory="";
if (ctrl_list.Count == 0)
SelectedCategory = dd_SubCategory.SelectedValue;
else
SelectedCategory = Session["Selected_SubCatg"] != null && Session["Selected_SubCatg"].ToString()!=""?Session["Selected_SubCatg"].ToString():((DropDownList)ctrl_list[ctrl_list.Count - 1]).SelectedValue;
try
{
DataRow[] Rows = DataHelper.TicketCategories.Select("PARENT_CATEGORY_ID='" + SelectedCategory + "'");
if (Rows.Length > 0)
{
AddSubCategory(Rows);
}
foreach (Control item in ctrl_list)
pnl_SubCatg.Controls.Add(item);
}
catch (Exception ex)
{ }
}
List<Control> _ctrl_list = null;
List<Control> ctrl_list {
get
{
if (Session["SUB_CATG_LIST"] == null)
{
_ctrl_list = new List<Control>();
Session["SUB_CATG_LIST"] = _ctrl_list;
}
return Session["SUB_CATG_LIST"] as List<Control>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["SUB_CATG_LIST"] = null;
Session["Selected_SubCatg"] = null;
}
if (ctrl_list.Count > 0)
{
foreach (Control item in ctrl_list)
pnl_SubCatg.Controls.Add(item);
}
}
private void AddSubCategory(DataRow [] Rows)
{
DropDownList dd_SubCategory1 = new DropDownList();
dd_SubCategory1.Width = Unit.Pixel(160);
dd_SubCategory1.DataTextField = "CATEGORY_NAME";
dd_SubCategory1.DataValueField = "CATEGORY_ID";
dd_SubCategory1.ID = Guid.NewGuid().ToString();
dd_SubCategory1.DataSource = Rows.CopyToDataTable();
dd_SubCategory1.DataBind();
dd_SubCategory1.SelectedIndexChanged += dd_SubCategory1_SelectedIndexChanged;
dd_SubCategory1.AutoPostBack = true;
ctrl_list.Add(dd_SubCategory1);
}
void dd_SubCategory1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Selected_SubCatg"] = ((DropDownList)sender).SelectedValue;
}
i am trying to add a dropdown list containing the subcategories of the last inserted dropdown list , my problem is dd_SubCategory1_SelectedIndexChanged is not firing and i can't get the and the selectedValue of the last dropdownlist is always the same
That is because its dynamically generated and it will lose its state after its rendered on your page.
To access the dropdown and its related events and properties, you will need to recreate it everytime your page is postback.
Hope its clear enough.

Page Index Changing do not works properly

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?

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.

right click on linkbutton in gridview is not opening into new tab

I am using a linkbutton within a gridview control.I want to open the link into a new tab. Link button:
<asp:LinkButton ID="lbtnEditCompany" CssClass="ahrefSearch" Text="Select" runat="server" OnClick="lbtnEditCompany_Click" />
Source Code :
protected void lbtnEditCompany_Click(object sender, EventArgs e)
{
try
{
LinkButton button = (LinkButton)sender;
SiteID = button.CommandArgument;
DataSet set = DataAccess.GetAllCorporateSites(SearchbyAlphabet, SessionManager.SaleID, SearchbyAssociate);
string str = "";
for (int i = 0; (i < set.Tables[0].Rows.Count) && (str == ""); i++)
{
if (SiteID == set.Tables[0].Rows[i]["ID"].ToString())
{
str = set.Tables[0].Rows[i]["CompanyName"].ToString();
}
}
SessionManager.WidgetId = Convert.ToInt32(SiteID);
SessionManager.SalesPersonSiteName = str;
base.Response.Redirect("~/Corporate/WidgetDetails.aspx", false);
}
catch (Exception exception)
{
HandlePageError(exception);
}
}
Try below code
Response.Write(String.Format("window.open('{0}','_blank')", ResolveUrl("~/Corporate/WidgetDetails.aspx")));

Drop Down List Event failed to execute

In my drop-down list, the SelectedIndexChanged event is not firing. I set AutoPostBack="True" but it's still not firing. Setting EnableViewState to True or False makes no difference either.
Here's my code:
<asp:DropDownList ID="ddlSheerName" runat="server" Width="250" AutoPostBack="True"
OnSelectedIndexChanged="ddlSheerName_SelectedIndexChanged"></asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
loggedInUserId = Convert.ToString(Session["LoggedInUserId"]);
if (loggedInUserId == "")
{
Response.Redirect("Login.aspx");
}
if (Page.IsPostBack == false)
{
BindCompanyDropDown();
}
}
protected void ddlSheerName_SelectedIndexChanged(object sender, EventArgs e)
{
Bindcolumnname();
}
public void BindCompanyDropDown()
{
try
{
objData = new DBFile();
DataSet dsCompanies = objData.GetCompaniesList(loggedInUserId);
if (dsCompanies != null)
{
if (dsCompanies.Tables[0].Rows.Count > 0)
{
ddlselectcompany.DataSource = dsCompanies;
ddlselectcompany.DataTextField = "CompanyName";
ddlselectcompany.DataValueField = "CompanyID";
ddlselectcompany.DataBind();
}
}
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
Viewstate must be enabled for this particular code to work and Javascript must be enabled for AutoPostBack to function.
The dropdown itself doesn't cause the event to fire.
You must actually change the selected item for the event to fire.
Is your event registred in the designer?
Select the dropdown and check the events assigned to it.

Categories

Resources