I have a gridview and I want to add a button 'VIEW' which redirects to the (Customers.aspx?CustomerID=) page. Every customer has a ID and each ID is associated with a report. I don't want the ID to show up in my gridview and I want it to be hidden.
Also, I want this button to show up only if the USER is an "Admin" or a "Salesperson" category. I s there a way i can bind my CustomerID to a UserCategory to generate reports for each ID separately.
I tried looking at some other posts as well but my button doesn't redirect for some reason.
Can someone please help me figure out what i am doing wrong here or if i am missing something. Any help will be greatly appreciated.
Thank you.
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnView" runat="server" CausesValidation="false" CommandName="Select" Text="VIEW" />
</ItemTemplate>
<ControlStyle CssClass="button" />
</asp:TemplateField>
protected void btnView(object sender, EventArgs e)
{
Button button = (Button)sender;
GridViewRow row = (GridViewRow)button.NamingContainer;
Label lblCustomerID = (Label)row.FindControl("lblCustomerID");
txtHFUserCategory.Value = Session["UserCategoryPC"].ToString();
String strUserCat = MTProcs.GetSingleDatabaseResult("SELECT tblUsers.UserCategoryID FROM tblUsers WHERE UserID = " + txtHFUserID.Value);
if (strUserCat == "4" || strUserCat == "12")
{
ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open(Customers.aspx?CustomerID=" + lblLeadID.Text + "');", true);
}
}
Hi you can do it with simply adding visible property in your button
like
<asp:button ID="yourBtnID" runat="server" Text="WotEver" visible='<%# Convert.toInt(Eval("admin"))==1 && Convert.toInt(Eval("SALESPERSON"))==1 %>'/>
Related
I have a gridview with the Template and it contains a LinkButton. When I click the button I want to open a link in new tab
<Templates>
<Obout:GridTemplate runat="server" ID="tempCurrTask">
<Template>
<asp:LinkButton Text='<%# Container.DataItem["CurrentTask"] %>' ID="lnkbtnview2"
runat="server" Font-Underline="true" OnCommand="SELREC" CommandArgument='<%# Container.PageRecordIndex %>'></asp:LinkButton>
</Template>
</Obout:GridTemplate>
And the SELREC function is
protected void SELREC(object sender, CommandEventArgs e)
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
Hashtable dataItem = grvLeads.Rows[rowIndex].ToHashtable() as Hashtable;
string id = Convert.ToString(dataItem["iTask_id"]); //.Split('|');
string rowIndexid = id.ToString();
//+ "/" + e.CommandName.ToString();
//ScriptManager.RegisterStartupScript(this, typeof(string), "openWindow", "window.open('Task.aspx?TaskID=" + rowIndexid.Trim() + "', '_newtab','left = 10, top=10,scrollbars=Yes,resizable=yes,width=1100,height=580'); ", true);
Response.Redirect("Task.aspx?TaskID=" + rowIndexid.Trim());
}
This link opens in the same tab. I want it to open in new tab, So I changed the asp:LinkButton to asp:HyperLink tag but the SELREC function is not called properly. I want to do it using LinkButton and I don't know how to do it by using the link button. So please anybody help me with sample code.
Try this approach;
<asp:LinkButton runat="server" href='<%# "Task.aspx?TaskID=" + MethodtoGenerateTaskId(parameter) %>' target="_blank">LinkButton</asp:LinkButton>
You should define MethodtoGenerateTaskId(parameter) in c# codebehind. Take CommandArgument as a parameter to this method.
protected string MethodtoGenerateTaskId(string command_arg)
{
int rowIndex = int.Parse(command_arg.ToString());
Hashtable dataItem = grvLeads.Rows[rowIndex].ToHashtable() as Hashtable;
string id = Convert.ToString(dataItem["iTask_id"]); //.Split('|');
string rowIndexid = id.ToString();
return rowIndexid.Trim();
}
and in markup;
<asp:LinkButton runat="server" href='<%# "Task.aspx?TaskID=" + MethodtoGenerateTaskId(Container.PageRecordIndex.ToString()) %>' target="_blank">LinkButton</asp:LinkButton>
and if it works; pls mark it as answer...
I want to pass all the gridview value into another page
I have one gridview in PatientDetails.aspx page and one button as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="true" AutoGenerateSelectButton="true"
AutoGenerateDeleteButton="true" OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" OnCommand="btnformatric_Command" />
on codebehind of PatientDetails.aspx is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
if (gvDoctorList.SelectedRow != null)
{
Server.Transfer("Patientstaticformatrix.aspx");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
Now on the second page name Patientstaticformatrix.aspx the code behind is as below
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
GridView gvDoctorList = (GridView)this.Page.PreviousPage.FindControl("gvDoctorList");
GridViewRow selectedRow = gvDoctorList.SelectedRow;
Response.Write("PatientId: " + selectedRow.Cells[0].Text + "<br />");
Response.Write("firstname: " + selectedRow.Cells[1].Text + "<br />");
Response.Write("lastname: " + selectedRow.Cells[2].Text + "<br />");
}
}
I had debug the code in second page....the value for gvDoctorList is null as well as the selectedRow is showing error of nullreference.
Can you please let me where I am wrong?
As i have seen your previous question also, So i can suggest you one thing, rather than keeping your gridview in session(which is expensive) you can use RowCommand event, and after having button here i don't think you need checkbox or chk_CheckedChanged event, you can pass the PatientID to your next page there you can write query to insert selected row data to your new table.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged"
AutoPostBack="true" />
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'>
</asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%#
Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
int pID = Convert.ToInt32(e.CommandArgument);
// either put ID in session and check
Session["PatientID"] = Convert.ToString(pID);
Server.Transfer("Patientstaticformatrix.aspx");
}
}
On page_Load Event
protected void Page_Load(object sender, EventArgs e)
{
string pID = Convert.ToString(Session["PatientID"]);
if(!string.IsNullOrEmpty(pID))
{
int patientID = Convert.ToInt32(pID);
//Call Stored procedure which will insert this record with this ID
// to another table
}
}
Try using Session Variables. You can set the GridView into a Session variable that can then be retreived later so long as the same session is still active.
You can use the following code to set the Session Variable on your first page :
Session["gvDoctorList"] = gvDoctorList;
And then to retreive from the variable on your second page :
GridView gvDoctorList = (GridView)Session["gvDoctorList"];
For more information on Sessions see the MSDN Session State Overview.
I have decided to add a second answer based on the correct comments from Ahmed, The session variables really shouldn't hold the amount of data of the gridview due to memory issues.
The following should work accordingly for what I assume you are doing :
Essentially when you are selecting the row to go to the next page you are trying to retrieve the data of that row onto the new page. Is this Assumption correct? If so then you have a number of options for you to use.
Again you could use the Session Variables to store the data of the row once extracted on the first page :
protected void btnformatric_Click(object sender, EventArgs e) {
if (gvDoctorList.SelectedRow != null) {
GridViewRow selectedRow = gvDoctorList.SelectedRow;
Session["PatientId"] = selectedRow.Cells[0].Text;
Session["firstname"] = selectedRow.Cells[1].Text;
Session["lastname"] = selectedRow.Cells[2].Text;
Server.Transfer("Patientstaticformatrix.aspx");
} else {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
Essentially here you are on the first page and you get the data from the row. You then store this data in session variables and you can use the following to find the data from the next page :
protected void Page_Load(object sender, EventArgs e) {
if (this.Page.PreviousPage != null) {
//Retrieve values from Session Variables
Response.Write("PatientId: " + Session["PatientId"].ToString() + "<br />");
Response.Write("firstname: " + Session["firstname"].ToString() + "<br />");
Response.Write("lastname: " + Session["lastname"].ToString() + "<br />");
}
}
You also have a second option of using Query Strings to pass the data. Although for this method I believe you will have to change the Server.Transfer("Patientstaticformatrix.aspx"); to be Response.Redirect("Patientstaticformatrix.aspx");
Below is an example on using Query Strings :
protected void btnformatric_Click(object sender, EventArgs e) {
if (gvDoctorList.SelectedRow != null) {
GridViewRow selectedRow = gvDoctorList.SelectedRow;
//Create URL with Query strings to redirect to new page
Response.Redirect("Patientstaticformatrix.aspx?parentid=" + selectedRow.Cells[0].Text + "&firstname=" + selectedRow.Cells[1].Text + "&lastname=" + selectedRow.Cells[2].Text);
} else {
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a row.')", true);
}
}
And to retrieve the values from the Request.QueryString object on the second page.
protected void Page_Load(object sender, EventArgs e) {
if (this.Page.PreviousPage != null) {
//Retrieve values from Query Strings
Response.Write("PatientId: " + Request.QueryString["parentid"].ToString() + "<br />");
Response.Write("firstname: " + Request.QueryString["firstname"].ToString() + "<br />");
Response.Write("lastname: " + Request.QueryString["lastname"].ToString() + "<br />");
}
}
Both of these solutions should meet your requirements, however they are both slightly different. The Session Variable solution is probably the preferred method as it will stop users from being able to see all of the data passed (if you need to pass confidential information) where as the Query String values will be available to anyone who can see the URL.
For more information on Session Variables and Query Strings see the below resources :
ASP.NET Session State Overview
Request.QueryString Collection
#Nunners answer is ownsome, but can also try with following way:
on anothoer page's pageload event fetch grid like:
GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");
All the technique is given below:
http://www.aspsnippets.com/Articles/Pass-Selected-Row-of-ASPNet-GridView-control-to-another-Page.aspx
Refer above doccument.
The real answer is that you should create the same gridview on another page. This is how 99% of ASP.NET sites work since that page at some point will be writing/updating/deleting data. Or just use the same page - why redirect to show the same data?
I found some solution:
In Source aspx after grid databind:
Session["gridtoexcel"] = yourgrid;
In destination aspx
var grid = ((GridView)Session["gridtoexcel"]);
gridToExcel.Columns.Clear();
foreach (DataControlField col in grid.Columns)
gridToExcel.Columns.Add(col);
gridToExcel.DataSource = grid.DataSource;
gridToExcel.DataBind();
this way i can 'clone' exact grid to another page. if you need some css style don't forget of add them in destination page
PS: gridToExcel is your destination grid
I am using a Repeater to get items from the database.
I place every item into the web user control page, with this code:
<%#DataBinder.Eval(Container.DataItem, "XXXX")%>
XXXX = attribute from the database, for example: Username.
In the .cs file of the web user control page, I want to get the ID(which is also in the database) from every single repeated element, any clue how I can do that?
For example:
The <%#DataBinder.Eval(Container.DataItem, "Username")%> is showing the username of every person who is in the database. And in the .cs-file I want to get the ID of that username. So I can use a SQL-query like this when a button is clicked next to that repeated username:
UPDATE Table SET Username = "Mike" WHERE ID = '" + #### + "'
I don't know what to write in place of the ####.
This: #### = ID from the repeated Username where the button is clicked.
Thanks in advance!
With a Repeater, a good way is to use a command button.
In you .aspx, define a command button in the repeater ItemTemplate:
<asp:Repeater ID="repUsers" runat="server" OnItemCommand="repUsers_ItemCommand">
<ItemTemplate>
<asp:Button runat="server" CommandName="select" CommandArgument='<%#Eval("Id")%>' Text="Select" />
<span><%#Eval("Username")%></span>
<br />
</ItemTemplate>
</asp:Repeater>
In your .cs, capture the command button clicks:
protected void repUsers_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "select")
{
int userId = int.Parse(e.CommandArgument.ToString());
// do your db update here...
}
}
In your aspx page do the following:
<asp:Repeater OnItemCommand="ButtonCommandEvent" ID="myRepeater" runat="server">
<ItemTemplate>
...
<asp:HiddenField ID="recordId" runat="server" value='<%# Eval("id") %>' />
...
</ItemTemplate>
Then in your code behind you can wire your button to do the following:
void ButtonCommandEvent(Object obj, RepeaterCommandEventArgs e)
{
var temp = e.Item.FindControl("recordId") as HiddenField;
//use the value in temp to insert into your database
//UPDATE Table SET Username = "Mike" WHERE ID = temp
}
This will work as long as you have 1 button next to each repeated item.
I am using Visual Studio 2008 with .NET Framework 3.5. I have a DataGrid with a LinkButton inside a TemplateColumn. I am trying to figure out how to disable the ability to click the LinkButton once it has been clicked. My DataGrid has 6 columns with the LinkButton column displaying years and the others displaying year end data for those years. When a year is clicked the DataGrid displays a breakdown of that year's data on a month by month basis. When the DataGrid is displaying the month by month breakdown I still need the year column to be visible but without the ability to click. I also have a button and a chart that, by default Visibility is set to false, but after a year is selected the Visibility is set to true with the button giving the ability to close out of the month by month breakdown and return to the year end breakdown. I have everything working except the disabling of the LinkButton.
Here is the code for my DataGrid's TemplateColumn:
<asp:TemplateColumn HeaderText="Year End">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbYear" Text='<%# DataBinder.Eval(Container, "DataItem.year") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
I have tried the following:
Attempt 1 using code behind:
protected void Page_Load(object sender, EventArgs e)
{
LinkButton lb = ((LinkButton) FindControl("lbYear"));
lb.Attributes.Add("onClick", "return false;");
}
Attempt 2 using Javascript:
function disableLinkButton() {
var lb = document.getElementById("lbYear");
if (lb.disabled != true) { lb.disabled = true; return true; }
}
else { return false; }
}
<asp:TemplateColumn HeaderText="Year End">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbYear" OnClientClick="disableLinkButton()" Text='<%# DataBinder.Eval(Container, "DataItem.year") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
-- The 3rd attempt was close which did gray out the LinkButtons but did not disable the ability to click them
Attempt 3 using the 'Enabled' property:
<asp:TemplateColumn HeaderText="Year End">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbYear" Enabled='<%# Convert.ToInt32(DataBinder.Eval(Container.DataItem, "year"))==1?Convert.ToBoolean("True"):Convert.ToBoolean("False") %>' Text='<%# DataBinder.Eval(Container, "DataItem.year") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateColumn>
Some other thoughts I have include using an 'OnClick' event or a 'CommandArgument'. I tried using 'OnClick' and in the code behind simply using:
LinkButton lb = ((LinkButton) FindControl("lbYear");
lb.Enabled = false;
Any help, thoughts, ideas, examples, etc. would be greatly appreciated. Thank you all in advance!
Adjusted Code:
<ItemTemplate>
<asp:LinkButton ID="lbYear" runat="server" OnClick="testClick" Text='<%# DataBinder.Eval(Container, "DataItem.year") %>'></asp:LinkButton>
<a id="MyContrl_lbYear" href="javascript:__doPostBack('MyContrl$lbYear','')" onclick="this.href='#';this.disabled=true;__doPostBack('MyContrl$lbYear','');"></a>
</ItemTemplate>
protected void showChart(object sender, EventArgs e)
{
LinkButton lbYear = ((LinkButton)FindControl("lbYear"));
lbYear.Attributes.Add("onclick", "this.href='#';this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(lbYear, "").ToString());
}
Option 3 and your last approach seem to be the way to go. The problem with LinkButtons is that even by putting Enabled on false, you wont block them from posting back. See: http://weblogs.asp.net/jeffwids/archive/2011/02/14/how-to-disable-an-asp-net-linkbutton-when-clicked.aspx
Therefore you have to do this manually with:
lb.Attributes.Add("onclick", "this.href='#';this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(lb, "").ToString());
Polity, thank you very much for your help, I really appreciate it. I found a different way to go about fixing this issue though.
.ASPX Code:
<TemplateColumn>
<ItemTemplate>
<asp:LinkButton runat="server" OnClick="test" Text='<%# DataBinder.Eval(Container, "DataItem.year") %></asp:LinkButton>
</ItemTemplate>
</TemplateColumn>
.ASPX.CS Code:
protected void test(object sender, EventArgs e)
{
foreach(var y in myDataGrid.Items)
{
LinkButton lb = ((y as TableRow).Cells[1].Controls[1] as LinkButton);
lb.Enabled = false;
}
}
Ok... I have a database table called employees..
This has columns called ID, Name, datejoined and Cannotbedeleted (check boxes)...
Now i want to add a delete column which deletes the rows when clicked.
But there are some entries which cannot be deleted if the Cannotbedeleted field is true (checked)... so the delete button should be invisible for these rows.
Please tell me a way of how to do this...
<asp:CheckBoxField DataField="CannotBeDeleted" HeaderText="CannotBeDeleted"
SortExpression="CannotBeDeleted" />
<asp:BoundField DataField="TimeAdded" HeaderText="TimeAdded"
SortExpression="TimeAdded" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I also tried using in delete template field...
' >
But i did not know what to do in code behind??
protected bool GetShowDeleteButton()
{
}
The solution is below.... but is there a way i can refresh the page once i click the delete button in the gridview....
Try looping through the rows in GridView_DataBound, and hide the button for each row that has the checkbox checked.
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach(GridViewRow myRow in GridView1.Rows)
{
//Find the checkbox
CheckBox ckbox1 = (CheckBox)myRow.FindControl("nameOfCheckBox");
if(ckbox1.Checked)
{
//Find the Delete linkbutton and hide it
LinkButton deleteButton = (LinkButton)myRow.FindControl("nameOfDeleteLinkButton");
deleteButton.Visible = false;
}
}
}
Now, here's the difference you need:
Implement the CheckBox column as a TemplateField with a CheckBox in it. You can bind the CheckBox to the data from your datasource.
Do it like this:
if($row['cannotbedeleted'] == true) {
$buttonDisplay = 'none';
}
echo "<button onclick='delete();' style='display: $buttonDisplay;'>Delete</button>";
Well that would be the solution in PHP but if the style of the button has "display: none;" in it the button will be hidden. :) HTH