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.
Related
I'm trying to pass variables back to an ASP.NET web page by PostBack. The status variables for button presses are stored in ViewState. The problem here is that I need to press the button twice before the changed status is sent to the page.
The ViewState is read by Page_Load:
protected void Page_Load (object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["Print"] = "Small";
Response.Write ("Status: " + ViewState["Status"].ToString());
}
else
Response.Write ("Status: " + ViewState["Status"].ToString());
}
The ViewState for a button press is set by:
protected void ImageButton_LargeStatus_Click (object sender, ImageClickEventArgs e)
{
ViewState["Status"] = "Large";
}
Why do I need to press the ImageButton twice to change the ViewState?
Thanks.
Because 1st time you are updating ViewState with wrong key...
Replace below line
ViewState["Print"] = "Small";
with
ViewState["Status"] = "Small";
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();
}
I have a Delete-Button in my gridview that i used to create with an TemplateField + LinkButton + OnRowCommand.
Now a normal user should not be able to use this button - or better not to see this button at all.
How to disable a coloumn in a gridView on the page Log event?
Try this:
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// get the column here and your condition to make that disabled
e.Row.Cells[index].Visible = false;
}
}
You can also hide like:
((DataControlField)gridView.Columns
.Cast<DataControlField>()
.Where(fld => (fld.HeaderText == "Title"))
.SingleOrDefault()).Visible = false;
Use this: column visible use before bind grid otherwise error occurring.
protected void Page_Load(object sender, EventArgs e)
{
gridView.DataSource = "yourDatasource";
gridView.DataBind();
gridView.Columns[ColumnIndex].Visible =false;
}
Try this
In your Page_Load
GridView1.Columns[0].Visible = false;
then column 0 of the grid become disable and the other column of the grid resize automatically.
I try to delete a record in Gridview and Database .I added a boundfield button and set the CommandName to Deleterecord in the RowCommand event I want to get the primary key of this record to delete that(primary key value does not show in the grid view. The following block of code shows this event(I try to show some data in a text box):
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Deleterecord")
{
TextBox1.Text = GridView1.DataKeys[GridView1.SelectedIndex].Value.ToString();
//bla bla
}
}
I also set
DataKeyName="sourceName"
in the gridview but it is not my primary key
If I click this button an exception occured like this:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How can I solve this problem
Use this
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Deleterecord")
{
LinkButton lb = (LinkButton)e.CommandSource;
GridViewRow gvr = (GridViewRow)lb.NamingContainer;
TextBox1.Text = grid.DataKeys[gvr.RowIndex].Value.ToString();
//bla bla
}
}
Here LinkButton should be replaced by the type of control which is performing this RowCommand Event
For more info go Here
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.