How to pass an argument on dynamic asp button EventHandler - asp.net

Good day i want to pass a value to a onclick button method :
This is my dynamically created button :
string Code = //Some value
Button button = new Button();
button.ID = "Start";
button.Click +=new EventHandler(button_Click);
button.CommandArgument = Code;
Page.Controls.Add(button);
this my event method :
void button_Click(object sender, EventArgs e)
{
string code = //Put the value in code
}
Thanks.

One widely used approach is to save such values in a server accessible controls or variable.
In concrete words:
If you want to pass the dynamic value from client side, use an ASP:HiddenField, set its value using JavaScript and access in the server code
<asp:HiddenField runat="server" id="hfMyArgument" value="" />
you can use the value on server side
void button_Click(object sender, EventArgs e)
{
string code = hfMyArgument.value.trim();
}
Create and use a session variable while creating the button
Session["MyArgument"] = "argument value";
Session["MySecondArgument"] = 143523;
to use these values on server side code C#
void button_Click(object sender, EventArgs e)
{
string code = Convert.toString(Session["MyArgument"]).trim();
}

since you are using the CommandArgument property of button, you can access this property in OnCommand event of this button. [ But NOT in OnClick ]
So, define an event handler for OnCommand event as:
button.Command += new CommandEventHandler(button_Command);
And in your event handler access the CommandArgument as:
void button_Command(object sender, CommandEventArgs e)
{
string _code = e.CommandArgument.ToString();
}

Related

Parameters through onclick event in asp

I've been trying to pass parameters through the onclick event using asp as follows:
<asp:Button runat="server" ID="btnUpdateFacturaID" style="display:none;" onclick="btnUpdateFacturaID_Click" CommandArgument="test" />
And on the other side:
protected void btnUpdateFacturaID_Click(object sender, CommandEventArgs e)
{
string s = e.CommandArgument.ToString();
}
But I receive an error of no overload for 'btnUpdateFacturaID_Click' mathes delegate 'System.EventHandler'
In fact, I had initially the functions as follows:
protected void btnUpdateFacturaID_Click(object sender, EventArgs e)
{
string s = e.CommandArgument.ToString();
}
But this way I can't (or I don't actually know, which is much more probable) pass parameters through the event. What amb I missing?
Try this :
protected void btnUpdateFacturaID_Click(Object sender, EventArgs e)
{
Button btn = (Button)sender;
//do whatever with
//btn.CommandArgument.ToString()
}

My textbox isn't visible

So i am trying to assign a text to a variable when TextChanged event is triggered. This is my code :
...
TextBox textbox = new TextBox();
textbox.TextChanged += textbox_TextChanged;
...
void textbox_TextChanged(object sender, EventArgs e)
{
value = textbox.Text;
}
The problem is that inside the event code block, the textbox isn't seen. It appears the following error : "The name 'textbox' does not appear in the current context" .
What should i do to see it inside the event code block ?
If you're creating a dynamic textbox it won't be referenced in your designer file. You'll need to store it as a property in your code behind class.
// OnLoad
this.MyTextbox = new TextBox();
this.MyTextbox .TextChanged += textbox_TextChanged;
// event
void textbox_TextChanged(object sender, EventArgs e)
{
value = this.MyTextbox .Text;
}

How can this codebehind be written better?

I have a form which has a single textbox that sends some data to the database upon hitting enter. Data is displayed below the textbox in a repeater control. Input data is displayed on the form immediately by binding the data to the repeater in the TextChanged event of that textbox.
In the CodeBehind, I am calling BindRepeater method twice, once on every new page load and once on the TextChanged event of the textbox.
How can this be rewritten to call the BindRepeater only once and still achieve the same effect?
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindRepeater();
}
}
protected void BindRepeater()
{
// data retrieval
// repeater binding
}
protected void CreateData(string newdata)
{
// data insert
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text != string.Empty)
{
string _newData = TextBox1.Text.Trim();
CreateData(_newData);
BindRepeater();
}
}
Use an event that would be fired after the text changed event to do the binding in. you can now remove it from the page load event.

Get the row that has been clicked in the gridview

I have added OnClick event dynamically for gridview.So when I click on any of the row on grid view, the event is fired but I can't get which row is clicked.
This is the code where I add event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty);
}
//This is the code which catches this event
protected void GridView1_OnClick(object sender, EventArgs e)
{
_ID="10" //Static data. I need this from the gridview1.row[ClickedRow].cell[0]
}
I fear you'll have to "manually" assign this value.
For this, add hidden input element to the form:
<input type="hidden" name="clicked_row" />
Change the code to:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(btnGrid, string.Empty) + "; document.forms[0].elements['clicked_row'].value = '" + e.Row.RowIndex + "';";
And finally, read the index from the Request in the GridView1_OnClick method:
_ID = Int32.Parse(Request.Form["clicked_row"]);
If each row has its own ID change e.Row.RowIndex to e.Row.Id.
I think, you could pass your id/rowindex as parameter to GetPostBackClientHyperlink() and implement the IPostBackEventHandler-interface in your page. The RaisePostBackEvent() method will get the id as input parameter passed in.
I haven't tested this, I just took a look at the example in MSDN documentation
Try passing in the row instead of the grid, like this:
e.Row.Attributes["OnClick"] = Page.ClientScript.GetPostBackClientHyperlink(e.Row, String.Empty);
And in your event handler:
protected void GridView1_OnClick(object sender, EventArgs e)
{
if (sender is GridViewRow)
{
int index = ((GridViewRow)sender).RowIndex;
}
}
I'm not positive, but I think the GridView OnClick will still fire since you're passing a child element of the grid.

Can't seem to capture a button click in a gridview in asp.net

I put some Image Buttons into my gridview, but I cannot capture the click event. Neither creating a click event, nor creating an OnRowCommand handler in the gridview works.
Clicking the buttons simply postbacks to the current page.
I add my buttons like this:
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string status = DataBinder.Eval(e.Row.DataItem, "visitstatusuid").ToString();
string visitUID = DataBinder.Eval(e.Row.DataItem, "visituid").ToString();
Color backColor = Color.White;
Color foreColor = Color.Black;
ImageButton b;
switch (status)
{
case "U": // Unallocated
backColor = ColorTranslator.FromHtml("#B2A1C7");
b = new ImageButton();
b.Width = Unit.Pixel(25);
b.Height = Unit.Pixel(30);
b.AlternateText = "Book";
b.ImageUrl = "../../Images/New/booking.gif";
b.ToolTip = "Booking";
b.CommandName = "Booking";
b.CommandArgument = visitUID;
b.CausesValidation = false;
e.Row.Cells[(e.Row.Cells.Count - 3)].Controls.Add(b);
etc.
You'll need to attach the handler when the button is created:
b.Click += MyButtonClickEventHandler;
Edit:
Instead of creating the button in the OnRowDataBound handler, use OnRowCreated.
This ensures the button is recreated on postbacks.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindData();
}
}
protected void BindData()
{
// Do your databinding here.
}
protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
var b = new ImageButton();
b.AlternateText = "Click Me!";
// Etc.
b.Click += MyButton_Click;
// Add the button to the column you want.
}
protected void MyButton_Click(object sender, ImageClickEventArgs e)
{
// Do your thing...
}
Unless you are adding an event handler elsewhere you would need to set AutoEventWireup="true" in the page directive of your aspx file.
That being said I prefer explicitly wiring events so rather than use AutoEventWireup add this line to your OnInit method:
gridview1.RowDataBound += this.gridview1_RowDataBound;
For your approach using RowDataBound to work, you need to rebind the grid on every page load, and ensure you do it no later than OnLoad in the lifecycle, in order for the click event to be registered in time.
An alternative approach I have had success with is to create a new method for doing the DataGrid button setup, e.g.
void PerformConditionalGridFormatting()
{
foreach (GridViewRow row in gvCaseList.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
... Add your buttons to the cells here
}
}
}
Then you call the method every time you perform a manual databind, and also on every postback i.e. in your OnLoad handler do:
if (Page.IsPostBack) PerformConditionalGridFormatting();
The advantage of this approach is that you don't have to databind on every postback, which saves resources.
create a RowCommand event handler for the gridview and check the command name to see if it's your button triggering it
something to the effect of
void gridview1_RowCommand(object sender, args e)
{
if (e.CommandName == "Booking")
{
// call your desired method here
}
}
Put the binding event of grid in to not post back.

Resources