Get databasevalue from Repeater asp.net - c#

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.

Related

View button with if else statement

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 %>'/>

get value of ddl, txtbox, calendar used in user control on main page using findcontrol in asp.net c#?

I want to do a task in which i want that using findControl during the use of webusercontrol on web form to get value of webusercontrol on main page I mean, I've created a webusercontrol and have used on web form. In webusercontrol.ascx page i use a textbox, calendar, and dropdownlist. Now I want to get value(which i choose from txtbox, ddl etc) should be display on main page. I mean, I want to use a button on default.aspx page and in a variable want to store value of txtbox, calendar etc. and using a FindControl want to get these values on main page. How I can do this plz help me by code plz I'm new in programing.
This is the code of ascx page
<%# Control Language="C#" ClassName="CalendarUserControl" %>
<asp:TextBox ID="txtData" runat="server"></asp:TextBox> <br />
<asp:Calendar ID="Calendar1" runat="server" BackColor="Beige" >
</asp:Calendar>
<br/>
<asp:DropDownList ID="ddlthings" runat="server">
<asp:ListItem> Apple</asp:ListItem>
<asp:ListItem> Banana</asp:ListItem>
<asp:ListItem> Mango</asp:ListItem>
<asp:ListItem> Grapes</asp:ListItem>
</asp:DropDownList>
default.aspx page
<div>
<uc1:CalendarUserControl ID="CalendarUserControl1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" OnClick="btn_Click" Text="Button" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
Define properties in your user control, that will return values of controls you want. For example
public partial class CalendarUserControl: UserControl
{
// this is code-behind of your user control
public string Data
{
get {return txtData.Text;}
}
public DateTime CalendarDate
{
get {return Calendar1.SelectedDate;}
}
// same approach for drop down list ddlthings
}
Then in your aspx page, just read those values, for example in your btn_Click event handler
protected void btn_Click(object sender, EventArgs e)
{
var textBoxValue = CalendarUserControl1.Data;
var calendarValue = CalendarUserControl1.CalendarDate;
//....
}
i did it, just write these lines in default.cs
protected void btn_Click(object sender, EventArgs e)
{
TextBox myLabel = (TextBox)CalendarUserControl1.FindControl("txtData");
string x = myLabel.Text.ToString();
Calendar c = (Calendar)CalendarUserControl1.FindControl("Calendar1");
string date = c.SelectedDate.ToString();
DropDownList b = (DropDownList)CalendarUserControl1.FindControl("ddlthings");
string ddl = b.SelectedValue;
Label1.Text = "Your text is: " + x + "<br />"+ " Your Selected Date is: " + date + "<br />"+ " Your Selected Item is: " + ddl;
}

Get record id using GridView Linkbutton on one page and get on another page in ASP.NET using C#

How do I submit the id from one page to another page in ASP.NET using C#? I have a GridView control and each record contains a link button:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtn_naatscat" runat="server" Text="arshad" CommandName="view_user_naats_gv" Font-Underline="false" />
</ItemTemplate>
</asp:TemplateField>
I've bound the id to link button:
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.FindControl("lbtn_naatscat")).CommandArgument
= DataBinder.Eval(e.Row.DataItem, "cate_id").ToString();
((LinkButton)e.Row.FindControl("lbtn_naatscat")).Text
= DataBinder.Eval(e.Row.DataItem, "title").ToString();
}
now I want to pass this id to another page when user click to this link button.
You can handle the LinkButton's Command event and use the CommandArgument:
void LinkButton_Command(Object sender, CommandEventArgs e)
{
if(e.CommandName == "view_user_naats_gv")
{
Resonse.Redirect("UserNaats.aspx?catID=" + e.CommandArgument.ToString());
}
}
You can create a Session for this purpose.
Do as follows:
Session["Id"]=e.CommandArgument.ToString() //Id you want to pass to next page
In this way your Session variable will get created. And you will be able to access it on the next page.
While retrieving it on next page:
Id=Session["Id"]
Other Alternatives:
View state
Control state
Hidden fields
Cookies
Query strings
Application state
Session state
Profile Properties
State management Techniques in ASP.NET:
http://msdn.microsoft.com/en-us/library/75x4ha6s%28v=vs.100%29.aspx
Hope its helpful.
Store it in a hidden field, and access it on the next page in the code behind file.
Here is another SO post with
Another example of passing hidden field in ASP
Best of luck!
I would use a HyperLinkField field like so
<asp:HyperLinkField DataNavigateUrlFields="Database ID Field"
DataNavigateUrlFormatString="~/PageName.aspx?ID={0}"
DataTextField="Database ID Field" HeaderText="ID" />
And then on the page that you're redirecting to, you would check the query string for ID
string id = Request.QueryString["ID"]
Set the PostBackUrl and CommandArgument properties of the LinkButton in your source page like so:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtn_naatscat" runat="server" Text="arshad" CommandName="view_user_naats_gv" Font-Underline="false" PostBackUrl="~/YourPage.aspx" CommandArgument='<%# Eval("submitid")%>' />
</ItemTemplate>
</asp:TemplateField>
Then on your page that is being submitted to you can place the following directive to the DestinationPage.aspx page:
<%# PreviousPageType VirtualPath="~/SourcePage.aspx" %>
I don't know what type of container the <ItemTemplate> tag is from (ListView?). However you can find the control in the DestinationPage.aspx page like so:
if (Page.PreviousPage != null && Page.PreviousPage.IsCrossPagePostback) {
// if you use the PreviousPageDirective you should be able to access the ListView
// property directly
// var listView = Page.PreviousPage.MyListView;
var listView = Page.PreviousPage.FindControl("MyListView") as ListView;
var linkButton = listView.FindControl("lbtn_naatscat") as LinkButton;
var submitId = linkButton.CommandArgument;
}
Using Row_Command event you can send it next page using query string.
protected void gvDeals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCommand")
{
string value=calculate();
Response.Redirect("~/MyPage.aspx?item=" + value);
}
}
I think it would make more sense to use a hyperlink in your GridView.
For example:
<ItemTemplate>
<asp:HyperLink ID="link_naatscat" runat="Server"
Text="arshad"
ToolTip="arshad"
NavigateUrl=<%#"~/YourPage.aspx?id=" + Eval("submitid")%>>
</asp:HyperLink>
</ItemTemplate>
Send the id this way
Response.Redirect("/yourpage.aspx?" + id);
And get it this way
String s = "";
foreach (String item in Request.QueryString.Keys)
{
s = Request.QueryString[item];
}
if (s != "")
{
id = Int32.Parse(s);
}

ASP Query String From DropDown

I have a webpage: Menu.aspx, where I have the following controls of relevance:
a DropDownList with some values
a hyperlink, which redirects me to a page called Edit.aspx.
In my Edit.aspx page, I have a cancel button, which redirects the user back to the Menu page
What I would like to do is when my user clicks on the hyperlink to go to the Edit page,index of the DropDownList is preserved in a query string In my Menu.aspx page I have the following aspx code, but I am not sure how to proceed
<asp:HyperLink
ID="lnkEdit"
NavigateUrl='<%# "Edit.aspx?" + Eval("UserID") + ...not sure... %>'
</asp:HyperLink>
<asp:DropDownList
ID="myDropDown"
...some <asp:ListItems/>
</asp:DropDownList>
EDIT: Clarified why Im using NavigateURL. Because my query string already does an Eval to determine the user ID.
I would use a LinkButton control with a server-side OnClick event.
<asp:LinkButton ID="lbtn1" runat="server" OnClick="lbtn1_Click"
CommandArgument='<%#Eval("UserID") %>' />
Server side method:
public void lbtn1_Click(object sender, EventArgs e)
{
LinkButton lbtn = (LinkButton)sender;
string userID = lbtn.CommandArgument;
string dropDownValue = myDropDown.SelectedValue;
string navigateUrl = string.Format("Edit.aspx?userid={0}&dropdown={1}",
userID, dropDownValue);
Response.Redirect(navigateUrl);
}
EDIT: As Royi Namir points out below, javascript is a better option if you can use that. This creates an unnecessary round trip to the server.
Try something like this
<asp:HyperLink ID="lnkEdit"
NavigateUrl='<%# "Edit.aspx?" + Eval("UserID") +
"&menuid=" + myDropDown.SelectedValue %>'> MyText </asp:HyperLink>
and also set AutoPostBack to true on your drop down. Whenever you will change your dropdown, new selected value bind with hyperlink navigate url.
Here's an easy way is to use Session
Example:
Session["SessionName"] = idDropDownList;
On another page, access only the content of the session
string idDropDownList = (string)Session["SessionName"];
I hope I helped.

need to change class in repeater elements

i have a repeater:
<ul>
<asp:Repeater ID="Repeater4" runat="server" DataSourceID="SqlDataSource5" onitemcommand="Repeater4_ItemCommand">
<ItemTemplate>
<li class="sports_menu1">
<asp:LinkButton ID="LinkButton1" runat="server" class="selected onclick="sideMenuSports1_Click">
<%#Eval("iconURL")%>
</asp:LinkButton></li>
</ItemTemplate>
</asp:Repeater>
</ul>
and i want to handle all the buttons in the same function:
protected void sideMenuSports1_Click(object sender, EventArgs e)
{
changeDataSources(); /*-----> this function supose to derict to URL(in a div on the same page) acording the id of the item of the repeater */
removeAllClasses(); /*this supose to remove all class named selected from the element in the <asp:button> element */
((LinkButton)sender).Attributes.Add("class", "selected");
}
to sumerise, what i need is:
i need to remove the class "selected" in all the repeater <asp:button> elements, then add it only to the element the user clicked
each button clicked redirect to other URL ,how i pass the button the id of the repeater element?
Had the same problem, solved it like this:
.aspx part:
<asp:Repeater ID="itemsRepeater" runat="server" OnItemCommand="itemsRepeater_ItemCommand">
<ItemTemplate>
<li>
<asp:LinkButton id="location_button" CommandArgument='<%# Eval("Key") %>' Text='<%# Eval("Value") %>' runat="server"></asp:LinkButton>
</li>
</ItemTemplate>
</asp:Repeater>
code-behind part:
protected void itemsRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
// for the sample purpose, setting the value here - replace it with your own
int locationId = 2;
// looping through all the repeater items (buttons)
foreach (RepeaterItem i in ((Repeater)source).Items)
{
// finding the repeater items having ID set to "location_button"
LinkButton btn = (LinkButton)i.FindControl("location_button");
// custom class added when location matches button's CommandArgument
if (btn.CommandArgument == locationId.ToString())
btn.CssClass = "button_main active";
else
btn.CssClass = "button_main";
}
}

Categories

Resources