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

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")));

Related

ASP .net datagrid sometimes show empty rows, without text

ASP. net data grid show empty rows without text randomly. Though is shows empty rows, on double clicking on empty row, the data from the row gets populated correctly to another text box.
Below is the UI code.
<asp:Panel ID="pnlDataControl" runat="server" Enabled="true" EnableViewState="true">
<div class="grdCtl">
<asp:GridView ID="grdlDataControl" runat="server" ShowFooter="True"
AutoGenerateColumns="False" GridLines="None" AllowPaging="True" AllowSorting="True"
Width="100%" BorderColor="Red" BorderWidth="0px" BorderStyle="Solid" EmptyDataText=""
onpageindexchanging="grdlDataControl_PageIndexChanging"
ondatabound="grdlDataControl_DataBound"
onrowdatabound="grdlDataControl_RowDataBound"
onselectedindexchanged="grdlDataControl_SelectedIndexChanged"
onrowcommand="grdlDataControl_RowCommand" style="margin-bottom: 18px;">
<SelectedRowStyle BackColor="Gray" Font-Bold="true" />
<Columns>
<asp:TemplateField HeaderStyle-CssClass="grdHead" HeaderStyle-Wrap="false" ItemStyle-CssClass="" HeaderStyle-Width="10px" ItemStyle-Width="10px">
<ItemTemplate></ItemTemplate>
<HeaderTemplate></HeaderTemplate>
<HeaderStyle CssClass="grdHead" Width="10px" Wrap="False" />
<ItemStyle Width="10px" />
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle HorizontalAlign="Center" />
<FooterStyle />
</asp:GridView>
</div>
</asp:Panel>
<br/>
</ContentTemplate>
</asp:UpdatePanel>
Attached is the screenshot how the results are populated in the datagrid.empty rows
Code behind
private void fntLoadData()
{
try
{
mLocationData = (IEnumerable<clsLocationData>)Session["DataRecords"];
if (mLocationData != null) mDataTotalRecords = mLocationData.Count();
this.grdlDataControl.DataSource = mLocationData;
this.grdlDataControl.DataBind();
if(clsApplication.LDSCount>=clsApplication.cParamMaximumResult)
{
Label ctlLabel = (Label)grdlDataControl.BottomPagerRow.FindControl("lblAlert");
ctlLabel.Text = fntGetLanguageValue("MoreRecords", "MESSAGES", "OR").Replace("1%", clsApplication.cParamMaximumResult.ToString());
}
}
catch (Exception ex)
{
fntCatchError(ex,"fntLoadData():");
}
}
protected void grdlDataControl_DataBound(object sender, EventArgs e)
{
GridViewRow gvrPager = grdlDataControl.BottomPagerRow;
if (gvrPager == null) return;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
Label txtPages = (Label)gvrPager.Cells[0].FindControl("txtPages");
Label lblPages = (Label)gvrPager.Cells[0].FindControl("lblPages3");
// populate dropdownlist
if (ddlPages != null)
{
for (int i = 0; i < grdlDataControl.PageCount; i++)
{
int intPageNumber = i + 1;
ListItem lstItem = new ListItem(intPageNumber.ToString());
if (i == grdlDataControl.PageIndex) lstItem.Selected = true;
ddlPages.Items.Add(lstItem);
}
}
if (txtPages != null) txtPages.Text = grdlDataControl.PageCount.ToString();
if (lblPages != null) lblPages.Text = "(" + mDataTotalRecords + " " + fntGetLanguageValue("lblItems", "LABEL", "OR") + ")";
// Check for next, prev images status
ImageButton btnFrst = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerFrst");
ImageButton btnPrev = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerPrev");
ImageButton btnNext = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerNext");
ImageButton btnLast = (ImageButton)gvrPager.Cells[0].FindControl("btnPagerLast");
if (grdlDataControl.PageIndex == 0)
{
btnPrev.Enabled = false; //btnPrev.ImageUrl = "./Images/icon_prev_i.gif";
btnFrst.Enabled = false; //btnFrst.ImageUrl = "./Images/icon_frst_i.gif";
}
else if (grdlDataControl.PageIndex + 1 == grdlDataControl.PageCount)
{
btnLast.Enabled = false; //btnLast.ImageUrl = "./Images/icon_last_i.gif";
btnNext.Enabled = false; //btnNext.ImageUrl = "./Images/icon_next_i.gif";
}
else
{
btnLast.Enabled = true; //btnLast.ImageUrl = "./Images/icon_last.gif";
btnNext.Enabled = true; //btnNext.ImageUrl = "./Images/icon_Next.gif";
btnPrev.Enabled = true; //btnPrev.ImageUrl = "./Images/icon_Prev.gif";
btnFrst.Enabled = true; //btnFrst.ImageUrl = "./Images/icon_frst.gif";
}
}
protected void grdlDataControl_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (clsApplication.cDataDisplayTypIcon == "true")
{
string sSymbol = ((clsLocationData)(e.Row.DataItem)).sTYPE;
System.Web.UI.WebControls.Image ImgIcon = new System.Web.UI.WebControls.Image();
string iconPath = "./Images/#" + sSymbol + ".gif";
string iconFile = "./Images/#NOTYPE.gif";
if (fntIsValidImage(Server.MapPath(iconPath))) iconFile = iconPath;
ImgIcon.ImageUrl = iconFile;
ImgIcon.Width = 16; ImgIcon.Height = 16; ImgIcon.ImageAlign = ImageAlign.AbsMiddle; ImgIcon.CssClass = "grdLocationIcon";
e.Row.Cells[0].Controls.Add(ImgIcon);
}
if (mDateRelevanceIdx > 0)
{
e.Row.Cells[mDateRelevanceIdx].Controls.Clear();
Double dRelevance = ((clsLocationData)(e.Row.DataItem)).sRELEVANCE;
if (clsApplication.cDataDisplayRelvBar == "true")
{
string sBarCSS = "grdRelevenceBar1";
if (dRelevance > 10) sBarCSS = "grdRelevenceBar2";
if (dRelevance > 20) sBarCSS = "grdRelevenceBar3";
if (dRelevance > 30) sBarCSS = "grdRelevenceBar4";
int iBarWidth = 40;
if (dRelevance > 10) iBarWidth = 30;
if (dRelevance > 20) iBarWidth = 20;
if (dRelevance > 30) iBarWidth = 10;
Label LabelBar = new Label();
//LabelBar.Width = new Unit((100 - dRelevance)/2);
LabelBar.Width = new Unit(iBarWidth);
LabelBar.CssClass = sBarCSS;
e.Row.Cells[mDateRelevanceIdx].Controls.Add(LabelBar);
}
if (clsApplication.cDataDisplayRelvTxt == "true")
{
Label LabelTxt = new Label();
LabelTxt.Text = (100 - dRelevance).ToString();
e.Row.Cells[mDateRelevanceIdx].Controls.Add(LabelTxt);
}
}
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='grdRowHigh';");
e.Row.Attributes.Add("onmouseout", "this.className='grdRowNorm';");
string sArgsData1 = "Select$" + e.Row.RowIndex.ToString();
e.Row.Cells[0].Attributes.Add("onclick", Page.ClientScript.GetPostBackClientHyperlink(grdlDataControl, sArgsData1));
string sArgsData2 = "DblSelect$" + e.Row.RowIndex.ToString();
e.Row.Attributes.Add("Ondblclick", Page.ClientScript.GetPostBackClientHyperlink(grdlDataControl, sArgsData2));
}
}
protected void grdlDataControl_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdlDataControl.PageIndex = e.NewPageIndex;
grdlDataControl.SelectedIndex = -1;
fntLoadDataControl();
}
protected void grdlDataControl_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select" || e.CommandName == "DblSelect")
{
GridView grdData = (GridView)sender;
int iRowIndex = int.Parse(e.CommandArgument.ToString());
int iPageIndex = grdData.PageIndex;
int iRowNumber = clsApplication.cDataRecordPerPage * iPageIndex + iRowIndex;
fntLoadDataControl();
if (e.CommandName == "DblSelect")
{
fntGetRowDataItem(iRowNumber, "dclick");
}
if (e.CommandName == "Select") fntGetRowDataItem(iRowNumber, "sclick");
}
this.grdlDataControl.DataBind();
}
void btnCtl_Click(object sender, EventArgs e)
{
Button btnCtl = (Button)sender;
mDataRecordSortFld = btnCtl.CommandName;
mDataRecordSortOrd = btnCtl.CommandArgument;
mDataRecordSortOrd = fntGetSortOrder(mDataRecordSortFld, mDataRecordSortOrd);
grdlDataControl.SelectedIndex = -1;
fntSortDataControl();
fntLoadDataControl();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
grdlDataControl.PageIndex = 0;
grdlDataControl.SelectedIndex = -1;
Session["DataRecords"] = null;
fntGetLocationData(false, null);
}
private void fntGetLocationData(bool isLocVer, EMEALVINTERFACE.LocationData LocData)
{
XmlDocument xmlLocation = oLV.GetLocationData(isLocVer,LocData);
fntLoadXML(xmlLocation);
}
private void fntLoadXML(XmlDocument xmlDocument)
{
try
{
if (xmlDocument != null && xmlDocument.InnerXml != "")
{
XDocument xDoc = XDocument.Parse(xmlDocument.InnerXml);
// IEnumerable<clsLocationData> vLocations = null;
var vLocations = from location in xDoc.Descendants("LOCATION")
select new clsLocationData
{
//copy locations
};
mLocationData = (IEnumerable<clsLocationData>)vLocations.ToList();
mLocationData = fntSortData(mLocationData, mDataRecordSortFld, mDataRecordSortOrd);
Session["DataRecords"] = mLocationData.ToList();
}
else
{
Session["DataRecords"] = null;
}
}
catch (Exception ex)
{
fntCatchError(ex,"fntLoadXML():");
}
}
Also, this application is being used by many remote clients and it is hosted on IIS in a server.
Make sure the global variable mLocationData is not being altered elsewhere in the code. It seems that either this variable, or Session["DataRecords"] is being reset elsewhere.
If the page loads correctly the first time the page loads, and the records disappear on subsequent postbacks, that points to the datasource being altered.

LinkButton in GridView non-clickable if it ends in a certain filetype

How would I make this LinkButton in GridView non-clickable if it ends in a *.rpt filetype?
I'm not sure where and which conditions I should add.
Thanks in advance!
Brett
LinkButton
.ascx code
<asp:LinkButton runat="server" ID="lbFolderItem" CommandName="OpenFolder" CommandArgument='<%# Eval("Name") %>'></asp:LinkButton>
<asp:Literal runat="server" ID="ltlFileItem"></asp:Literal>
Code Behind
ascx.cs code
protected void gvFiles_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as FileSystemItemCS;
if (item.IsFolder)
{
var lbFolderItem = e.Row.FindControl("lbFolderItem") as LinkButton;
lbFolderItem.Text = string.Format(#"<img src=""{0}"" alt="""" /> {1}", Page.ResolveClientUrl("~/Images/folder.png"), item.Name);
}
else
{
var ltlFileItem = e.Row.FindControl("ltlFileItem") as Literal;
if (this.CurrentFolder.StartsWith("~"))
ltlFileItem.Text = string.Format(#"{1}",
Page.ResolveClientUrl(string.Concat(this.CurrentFolder, "/", item.Name).Replace("//", "/")),
item.Name);
else
ltlFileItem.Text = item.Name;
}
}
}
protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "OpenFolder")
{
if (string.CompareOrdinal(e.CommandArgument.ToString(), "..") == 0)
{
var currentFullPath = this.CurrentFolder;
if (currentFullPath.EndsWith("\\") || currentFullPath.EndsWith("/"))
currentFullPath = currentFullPath.Substring(0, currentFullPath.Length - 1);
currentFullPath = currentFullPath.Replace("/", "\\");
var folders = currentFullPath.Split("\\".ToCharArray());
this.CurrentFolder = string.Join("\\", folders, 0, folders.Length - 1);
}
else
this.CurrentFolder = Path.Combine(this.CurrentFolder, e.CommandArgument as string);
PopulateGrid();
}
}

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.

OnRowCommand="grd_RowCommand" event not firing when click on row

here i bind grid columns dynamically using code behind because my GetSocailAnalytics method return dynamic column according to parameter passed.after binding column of grid using data table my grd_OnRowCommand event not firing when i click on grid row. grid is successfully bind. can any one help me out this issue.here is my code...
<asp:GridView ID="grd" EnableViewState="true" AutoGenerateColumns="false" OnRowCommand="grd_RowCommand"
runat="server" OnRowDataBound="grd_RowDataBound">
<Columns>
</Columns>
</asp:GridView>
private void GetData()
{
try
{
int TotalRecords = 0;
DataTable dt = ClsSocialManager.GetSocialAnalytics(Convert.ToInt32(hdnReferrerId.Value), Convert.ToInt32(hdnReferralId.Value), out TotalRecords, Convert.ToInt32(hdnPageIndex.Value));
if (dt != null && dt.Rows.Count > 0)
{
BindTemplateFiled(dt);
grd.Visible = true;
}
else
{
grd.Visible = false;
}
lblStatus.Text = TotalRecords.ToString() + " Record(s) found";
}
catch (Exception ex)
{
lblStatus.Text = "Some Error Occured " + ex.Message;
lblStatus.CssClass = "ErrMsg";
}
}
//Start Crearting GridColumn Dynamically
class LinkColumn : ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
LinkButton link = new LinkButton();
link.ID = "lnkbtnReferrerHost";
link.DataBinding += new EventHandler(this.link_DataBinding);
link.CommandName = "sad";
container.Controls.Add(link);
}
private void link_DataBinding(Object sender, EventArgs e)
{
LinkButton lnkReferrerHost = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnkReferrerHost.NamingContainer;
lnkReferrerHost.Text = Convert.ToString((((System.Data.DataRowView)(row.DataItem))).Row[1]);
lnkReferrerHost.CommandArgument = Convert.ToString((((System.Data.DataRowView)(row.DataItem))).Row[0]);
//lnkReferrerHost.CommandName = "Filter";
}
}
private void BindTemplateFiled(DataTable dt)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (dt.Columns[i].ColumnName == "Referrer Host")
{
var lnkbtnReferrerHost = new TemplateField();
lnkbtnReferrerHost.ItemTemplate = new LinkColumn();
lnkbtnReferrerHost.HeaderText = dt.Columns[i].ColumnName;
grd.Columns.Add(lnkbtnReferrerHost);
}
else
{
BoundField field = new BoundField();
field.DataField = dt.Columns[i].ColumnName;
field.HeaderText = dt.Columns[i].ColumnName;
grd.Columns.Add(field);
}
}
grd.DataSource = dt;
grd.DataBind();
}
//End Crearting GridColumn Dynamically
protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Filter")
{
GridViewRow gvr = (GridViewRow)grd.Rows[((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex];
LinkButton lbtn = (LinkButton)gvr.FindControl("lnkReferrerHost");
hdnReferrerId.Value = Convert.ToString(Convert.ToInt32(e.CommandArgument));
lblCurrentPage.Text = lbtn.Text;
GetData();
}
}
catch
{
}
}
The RowCommand event is raised when a button is clicked in the
GridView control.
it is not not firing when you click on grid row
solution is adding button (LinkButton) column to the gridview with CommandName ="Filter"

ASP.NET C# trying to hide a link button

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;

Categories

Resources