My textbox isn't visible - asp.net

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;
}

Related

How to pass an argument on dynamic asp button EventHandler

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();
}

why chk.Checked ChangedEventHandler is not triggered and i get the exception Object reference not set to an instance of an object

I try to make a simple application in which I have a dropdown list with tems - numbers from 1 to 4.
Depending on the number the user choose - I create dynamically this number of checkboxes with binded checkedchanged event. So when the user checks some of the checkboxes so checkedchanged event is raised and I store the text of the checked checkbox in session and then when I click a button I want to see the text only from the checked checkboxes.
But it seems that the checkedchanged event handler is never triggered.
Thank you in advance
public partial class proba : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
dd1.Items.Add("1");
dd1.Items.Add("2");
dd1.Items.Add("3");
dd1.Items.Add("4");
}
protected void dd1_SelectedIndexChanged1(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(dd1.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + i;
chk.Text = "box" + i;
chk.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(chk);
}
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
lblpr.Text += chk.Text;
Session["chk"] = chk.Text;
}
protected void btnpr_Click(object sender, EventArgs e)
{
lblpr.Text = "length" + ((String [] )Session["chk"]).Length;
for (int k = 0; k < ((String[] )Session["chk"]).Length; k++)
{
lblpr.Text += ((String [])Session["chk"])[k];
}
}
}
You need to set AutoPostBack property of checkbox as true in order to post back when check changed
chk.AutoPostBack = true;
And read this also
adding an event handler to a dynamically created checkbox (aspx, c#)
change page load, you don't need to add items again and again in each page post back
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Load dd1
}
}
But you need to add dynamic controls on each page post back, better do it on OnInit as above answer in the link suggested
since you are creating checkbox dynamically, it get lost when there is the post back.
So you need to add those again before pageload event so that during page load event they are visible to .net and hence .net can fire their corresponding event.
B4 you dive into dynamic control it is good idea to get the basic which can be found at https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx

Make event for a multiple buttons and know which button been clicked

I am writing an web app in asp.net,
In the code behind I have this code:
foreach(UserDetails _UD in m_TeachersDetailsList)
{
Button button = new Button();// a Button control
button.Text = "click";
button.ID = "SelectedTeacher";
TableCell tableCell = new TableCell();// a Cell control
tableCell.Controls.Add(button);
TableRow tableRow = new TableRow();
tableRow.Cells.Add(tableCell); // a table row
TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx
}
How can I make an event that when you click on the button you go to a function,
and how can I know which button had been click and Brought me to my function.
thanks.
You do this
int id = 0;
foreach(UserDetails _UD in m_TeachersDetailsList)
{
Button button = new Button();// a Button control
button.Text = "click";
button.ID = "selectedTeacher" + id++;
TableCell tableCell = new TableCell();// a Cell control
tableCell.Controls.Add(button);
TableRow tableRow = new TableRow();
tableRow.Cells.Add(tableCell); // a table row
TableSearchResult.Rows.Add(tableRow); // a table that had been created in the aspx
button.Click += new EventHandler(this.button_Click);
}
And common event handler
protected void button_Click(object sender, EventArgs e)
{
//This way you will get the button clicked
Button button = (Button)sender;
}
Important
You will need to add the controls in OnInit.
Hope this works for you.
ASPX
asp:Button ID="btnTest" runat="server" onclick="btn_Click"
Codebehind
protected void btn_Click(object sender, EventArgs e)
{
Button mybutton = (Button)sender;
Response.Write(mybutton.ID);
}
Just use btn_Click as the onclick for each of your buttons. Then use the "sender" to determine which control sent the request.
Don't set the button's id, let it default. Set the button's CommandArgument property instead:
foreach (UserDetails _UD in m_TeachersDetailsList)
{
Button button = new Button();// a Button control
button.Text = "click";
button.CommandArgument = _UD.UserDetailID.ToString(); // some unique identifier
// this is optional, if you need multiple actions for each UserDetail:
button.CommandName = "SomeAction"; // optional
button.Command += new EventHandler(detailButton_Handler);
// ...etc...
}
Then your handler needs to check the CommandName and CommandArgument values:
public void detailButton_Handler(object sender, EventArgs e)
{
string DetailID = e.CommandArgument.ToString();
switch (e.CommandName.ToString())
{
case "SomeAction":
/// Now you know which Detail they clicked on
break;
case "OtherAction":
break;
}
}

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