Command Argument not working link button - c#

I have a link button and a set of records. When the link button of a specific record is clicked, i want the id of that record to be passed to the code behind. This is the code that i have used:
<asp:LinkButton ID="Likes" runat="server" OnCommand="LinkButton1_Click"
CommandArgument='<%#Eval("datarow["ID"]") %>' CommandName="Like">
Click</asp:LinkButton>
and in the cs file i have used:
protected void LinkButton1_Click(object sender, CommandEventArgs e)
{
int x = Int32.Parse(e.CommandArgument.ToString());
}
But the command argument is null here. can you please help me?

You would handle the wrong event. I think your LinkButton is inside a another control as #greg84 said, for example, you could handle event ItemDataBound of DataGrid or Repeater .
protected void Control_ItemDataBound(object sender, ControlItemEventArgs e)
{
LinkButton Likes = (LinkButton)e.Item.FindContro("Likes");
// Write code here to handle for like click
// ...
}

Related

The RowDataBound events of the gridview is not fired after turning to the next page

I use a gridview to display the search result. After clicking search button, the gridview will show page 1, but when I click page 2 link, the gridview disappeared and it was back when I click search button again and show page 2's content.
here is my code
<asp:GridView ID="searchresult" runat="server" AutoGenerateColumns="true" AllowPaging="true" OnRowDataBound="searchresult_RowDataBound" OnPageIndexChanging="searchresult_PageIndexChanging"
HeaderStyle-BackColor="#f9e4d0"
HeaderStyle-Height="20px"
Font-Size="11px"
AlternatingRowStyle-BackColor="#cfdfef"
Width="800px" style="text-align:left">
</asp:GridView>
and code behind
protected void search_Click(object sender, EventArgs e)
{
List<someclass> totalResult = new List<someclass>();
..... //some code to generate the datasource
searchresult.DataSource = totalResult;
searchresult.AllowPaging = true;
searchresult.DataBind();
}
protected void searchresult_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void searchresult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
searchresult.PageIndex = e.NewPageIndex;
DataBind();
}
I have no idea why the page 2 won't show up until I click search button again. when I clicked the page 2 link, the page did postback but the RowDataBound event was not fired
You have to give your grid a datasource. It appears you are only doing this on search_Click, so your grid is only going to have data then. Try something like:
protected void search_Click(object sender, EventArgs e)
{
PopGrid();
}
protected void searchresult_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
searchresult.PageIndex = e.NewPageIndex;
PopGrid();
}
protected void PopGrid()
{
List<someclass> totalResult = new List<someclass>();
..... //some code to generate the datasource
searchresult.DataSource = totalResult;
searchresult.AllowPaging = true;
searchresult.DataBind();
}
searchresult_PageIndexChanging event handler will make that functionality work. However I recommend you use a gridview control inside a Panel with vertical scroll bar. My user love it and it is a lot faster moving up and down the gridview without defining any page index changing.
I hope it work for you.

Remove redundancies in code

I'm still new at this so I will try to explain my problem the best I can. English is not my first language so I apologize if I use some terms incorrectly.
I have a 100 line code that is executed every time a button is pressed. My problem is, I have 20 buttons and they all contain the same code (they are only slightly different in means of grabbing info from different source). Is there any way to do this instead of copying the same code too many times.
Basically my code is this:
private void button1_Click(object sender, EventArgs e)
{
//file data source url
sourceUrl = ("www.myurl.com")
//Grab data
code
code
code
//Store data
code
code
code
//Write data
code
code
code
}
Every button has the same code except for the "sourceUrl" part. If I want to add more buttons I have to copy>paste the whole code and my application is starting to get HUGE. Is there any way to shrink the code by only having the code once, and then calling an action or method every time the button is pressed. So instead of having 100 line code multiple time, I'll have one line code for each button and one 100 line code on the top that will be the source for that one line code.
Thanks in advance
Use the Tag property of your buttons to store the source url string and then set, for every button, the same event handler
private void buttonCommonHandler_Click(object sender, EventArgs e)
{
Button b = sender as Button;
CommonMethod(b.Tag.ToString());
}
private void CommonMethod(string sourceUrl)
{
// Execute the common code here....
}
You could set the common handler and the Tag using the form designer window or you could do that dynamically mimicking the code prepared for you by the designer in the InitializeComponent call
button1.Click += buttonCommonHandler;
button1.Tag = "www.myurl.com";
button2.Click += buttonCommonHandler;
button2.Tag = "www.anotherurl.com";
That's what functions are for. Use this layout:
private void YourFunc(string sourceUrl)
{
//Grab data
code
//Store data
code
//Write data
code
}
Now your buttons' event handlers look like this:
private void button1_Click(object sender, EventArgs e)
{
YourFunc("www.myurl.com");
}
private void button2_Click(object sender, EventArgs e)
{
YourFunc("www.myurl2.com");
}
Sure there is a way. Just make the whole function a function that takes the url as a string parameter. And then call that function from your code behind.
private void button1_Click(object sender, EventArgs e)
{
//file data source url
ProcessData("www.myurl.com");
}
private void ProcessData(string sourceUrl)
{
//Grab data
code
code
code
//Store data
code
code
code
//Write data
code
code
code
}
Here we can use use CommandName property, by passing URL in every button's CommandName property and passing it as a parameter to your Common Method to fetch data , So you can create a single function and call it through you btn_Click event .
<asp:Button ID="button1" runat="server" Text="clickMe"
CommandName="put your URL here" OnCommand="button1_Click" />
<%--OnClick="button1_Click" />--%>
See here we can pass your 'URL' in CommandName property ,few things to keep in mind , Here we are using OnCommand event rather than OnClick event of button , so that we can use 'CommandName' property here .1. OnCommand MSDN
2. Commandname MSDN
// private void button1_Click(object sender, EventArgs e)
private void button1_Click(object sender, CommandEventArgs e)
{
string sourceUrl = Convert.tostring(e.CommandName)
// Call function to grab data pass URL as parameter.
GrabDate (sourceUrl ) ;
So now we can get the URL value from button CommandName property .
3 . EventArgs Class
4 .CommandEventArgsClass

How to send a value from a LinkButton to the server?

I have many LinkButton such as:
<asp:LinkButton runat="server" onclick="cmdCancellaComunicazione_Click">X</asp:LinkButton>
they call the same server method, cmdCancellaComunicazione_Click. but I need to distinguish them (passing to the server, for example, a value).
How can I do it? I know there is CommandArgument, but I can't set to it a value such as <%= myValue %>
You can use the sender argument of the event-handler. Cast it to LinkButton:
protected void cmdCancellaComunicazione_Click(Object sender, EventArgs e)
{
LinkButton lbtn = (LinkButton) sender;
}
Then you can use it's CommandName, ID or Text to distinguish.
Your code has no ID specified on your LinkButton which seems odd.
You should be able to assign the CommandArgument server side with:
yourLinkButton.CommandArgument = yourValue;
And then it will be read it server side in your OnClick handler.
protected void cmdCancellaComunicazione_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
if (btn.CommandArgument.Equals(something here))
{
// do something
}
else
{
// do something else
}
}
Is this being created in a grid or something that is being bound? If so I would implement the OnDataBinding event for the LinkButton like:
<asp:LinkButton ID="yourLinkButton"
runat="server" OnDataBinding="yourLinkButton_DataBinding"
onclick="cmdCancellaComunicazione_Click">X</asp:LinkButton>
Server side code (I try to avoid inline code whenever possible):
protected void protected void lblID_DataBinding(object sender, System.EventArgs e)
{
LinkButton btn = (LinkButton)sender;
btn.CommandArgument = yourValue;
}
Is there something more to your scenario that you have not included in your question?
In your method, you can cast the sender to a LinkButton and inspect the value there.
OnCommand would be a good option here.
protected void ButtonCommand(object sender, CommandEventArgs e)
{
string theCommand = e.CommandArgument.ToString();
}
Just add the OnCommand and CommandArgument to the LinkButton.
<asp:LinkButton id="LinkButton1" Text="The Text" OnCommand="ButtonCommand" CommandArgument="YourInfo" runat="server"></asp:LinkButton>

Why my Query string is not working?

I am facing problem in query string. Following is my asp code
<asp:Label ID="Lable1" runat="server" Text="" ></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
C# code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Lable1.Text += Request.QueryString["refresh"] ;
Response.Redirect("QueryString1t.aspx?refresh=" + 1 + "");
}
Up to my knowledge Lable1 text should change on button click every time. Lable1 text should not show any thing on page load . on button click it should be like for first click 1 for second click 11 and so on..
But it is not showing as my expectation .So tell me please where i am wrong?
You are redirecting after setting label text, wrong approach.
Try this: -
protected void Page_Load(object sender, EventArgs e)
{
Lable1.Text = Request.QueryString["refresh"];
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("QueryString1t.aspx?refresh=" +
string.IsNullOrEmpty(Request.QueryString["refresh"]) ? 0 :
Convert.ToInt32(Request.QueryString["refresh"]) + 1 + "");
}
OR this: -
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Lable1.Text = string.IsNullOrEmpty(Lable1.Text) ? "0" :
(Convert.ToInt32(Lable1.Text) + 1).ToString();
}
Have a look at this:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
Particularly the fourth and fifth events in the cycle.
If you want the text to be updated as you are looking for there, then you need to put that code in the page load, not the click event handler.
In brief, you have to think of it like this: Every time you do a redirect, you lose viewstate,
http://msdn.microsoft.com/en-us/library/ms972976.aspx
which is the means by which ASP.NET keeps track of your updates to the controls, like in your event handler. So your update is immediately lost.
The next piece of code you will hit is your load event, so that is where you need to set the label's text property.
How do I persist the value of a label through a response.redirect?

Run the button event handler before page_load

I have a table with all the objects I have in my db. I load them in my Page_Load function. I have a text field and a button that when clicking the button, I want the handler of that click to put a new object with the name written in the text field in the db.
Now, I want that what happens after the click is that the page loads again with the new item in the table. The problem is that the button event handler is run after the Page_Load function.
A solution to this would be to use IsPostBack in the Page_Load or use the pre load function. A problem is that if I would have 3 different buttons, I would have to differ between them there instead of having 3 different convenient functions.
Any solutions that don't have this problem?
Code:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
// LOAD DATA FROM DB
}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
}
Maybe you should try loading your data during PreRender instead of Load
protected void Page_Load(object sender, EventArgs e)
{
this.PreRender += Page_PreRender
if (Session["userId"] == null)
Response.Redirect("Login.aspx");
}
protected bool reloadNeeded {get; set;}
protected void CreateObject(object sender, EventArgs e)
{
// SAVE THE NEW OBJECT
reloadNeeded = true;
}
protected void Page_PreRender(object sender, EventArgs e)
{
if(reloadNeeded || !IsPostBack)
// LOAD DATA FROM DB
}
You can check the event target and do what you need then:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string eventTarget = Page.Request.Params["__EVENTTARGET"];
if(whatever)
{
//do your logic here
}
}
}
Get control name in Page_Load event which make the post back
Use the Page_PreRenderComplete event to retrieve your table. That way your page will always have the most recent data available after all user events have fired.
Why don't you move what you have in the click event into a new method. Then call that method as the first line in your page load?
An old question but I faced the same problem in my C#/ASP.NET Website with master/content pages: a click on a link on the master page should change a query parameter for a gridview on the content page. As you stated the button click event is handled after Page_Load. But it is handled before Page_LoadComplete (see the information about ASP.NET Page Life Cycle), so you can change the page content there.
In my case I solved the problem by setting a session variable in the click event in the master page, getting this variable in the Page_LoadComplete event in the content page and doing databind based on that.
Master page:
<asp:LinkButton ID="Btn1" runat="server" OnCommand="LinkCommand" CommandArgument="1" >Action 1</asp:LinkButton>
<asp:LinkButton ID="Btn2" runat="server" OnCommand="LinkCommand" CommandArgument="2" >Action 2</asp:LinkButton>
protected void LinkCommand(object sender, CommandEventArgs e)
{
HttpContext.Current.Session["BindInfo", e.CommandArgument.ToString());
}
Content page:
protected void Page_LoadComplete(object sender, EventArgs e)
{
string BindInfo = HttpContext.Current.Session["BindInfo"].ToString();
YourBindDataFunction(BindInfo);
}

Categories

Resources