The following code is not executing!!
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow r = GridView1.SelectedRow;
TxtName.Text = r.Cells[0].Text;
TextBox2.Text = r.Cells[1].Text;
TextBox3.Text = r.Cells[2].Text;
TextBox4.Text = r.Cells[3].Text;
}
You must use EnableViewState="true" and bind just one time with ! IsPostBack in order to not erase your event foreach post.
because when your re build your grid you erase all events
In your page load :
if(! IsPostback)
{
//Bind your Gridview
}
Persist your datas with EnableViewState="true"
<asp:gridview id="YourGridView" EnableViewState="true" ...../>
we need to make the select button enable then only the GridView1_SelectedIndexChanged is fired i.e AutoGenerateSelectButton="true"
Related
I am having trouble attaching a click event onto an image that I have stored within a grid view. Basically it is a delete button that will allow the user to delete a specific row depending on where the button is. I have the code in c# ready for it, however, I cannot seem to attach a click event to it.
This is the markup code of the button
<asp:TemplateField HeaderText="Remove" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgbDeleteP" runat="server" BORDER="0" CausesValidation="false" ImageUrl="~/img/Del.png" Height="25px" ImageAlign="Middle"
onClick ="gv_Quals_RowCommand" CommandArgument="<%#Container.DataItemIndex%>" CommandName="Remove" />
</ItemTemplate>
onClick ="gv_Quals_RowCommand"
Here is the code in c# for the click event
protected void gv_Quals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if ((e.CommandName == "Remove"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gv_Quals.Rows[index];
DataTable dtCurrentTable = (DataTable)Session["CurrentTable"];
dtCurrentTable.Rows[index].Delete();
if ((dtCurrentTable.Rows.Count < 0))
{
}
else if ((row.Cells[0].Text != "*New*"))
{
int appId = 5000;
//int appId = 1;
string insProg = ("delete from projectunitassignment where UnitId =" + int.Parse(row.Cells[0].Text));
SqlCommand cmd = new SqlCommand(insProg, conn);
cmd.Connection.Close();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
RebindCat(appId);
}
}
}
This is the compilation error that I keep getting
CS0123: No overload for 'gv_Quals_RowCommand' matches delegate 'ImageClickEventHandler'
I cannot set the click event through the properties as it is stored within the grid view so I cannot access it through there. Also the click event does not run as I have tested with debugging
The problem is with GridViewCommandEventArgs should be just EventArgs
public void imgbDeleteP_Click(object sender, EventArgs e)
Edit:
I see that in your code you use the Command Argument, so if you want to use that you should see this post
Basically use onCommand instead of onClick or cast the sender to button to get the command argument, something like:
var argument = ((ImageButton)sender).CommandArgument;
Did you try to associate the click event for that grid during page load ?
I think that is because of GridViewCommandEventArgs which commonly used for RowCommand , change it to EventArgs, so that event should be something like this:
protected void gv_Quals_RowCommand(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
string cmName= btn.CommandName;
string cmArgument= btn.CommandArgument;
if ((cmName == "Remove"))
{
.....
}
}
or to get row index:
GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvRow.RowIndex;
The first parent is the GridView Cell and the second parent of the GridView Cell is the GridView Row.
I have Gridview that has 6 other BoundField Columns and one Linkbutton column.
I want to pass all the Row information to the next page when users click on LinkButton.
What are the best ways to do this?
If we pass it as QueryString, it is going to be Too long.
Thanks
You can use the LinkButton Column itself to your advantage.
The idea is to send the RowIndex of the GridViewRow in PostBackUrl property of LinkButton as a QueryString Parameter.
Use the Container.DataItemIndex which represents the Index of the Row.
At the Next/Destination page , get the RowIndex from QueryString to get the GridViewRow and then read the Column values.
Step 1.) The markup corresponding to LinkButton should be as below:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" Text="Send Details"
PostBackUrl='<%# "~/NextPage.aspx?RowIndex=" +
Container.DataItemIndex %>'>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Step 2.) In the Page Load event of NextPage.aspx, get first the GridViewRow where LinkButton was clicked and then read the row values
Note that using the PostBackUrl property in essence makes a cross page postback and therefore you can use the property Page.PreviousPage
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.PreviousPage != null)
{
int rowIndex = int.Parse(Request.QueryString["RowIndex"]);
GridView GridView1 = (GridView)this.Page.PreviousPage.FindControl("GridView1");
GridViewRow row = GridView1.Rows[rowIndex];
//Since you use Bound Fields, use row.Cells[] to read values
String Column_One_Value = row.Cells[0].Text;
String Column_Two_Value = row.Cells[1].Text;
}
}
Too long is subjective, anyways, if you don't want to use QueryString you can use Session Variables, Session vars are kept across the web site
protected void gvUsers_PageIndexChanging(object sender, EventArgs e)
{
Session["TheSelectedRow"] = ((Control)sender).Parent as GridViewRow;
// Your code to redirect
}
or you can wrap them in Properties, to work better and avoid casting every time in different lines and spelling mistakes
public GridViewRow TheSelectedRow
{
get { return Session["TheSelectedRow"] == null ? null : Session["TheSelectedRow"] as GridViewRow; }
set { Session["TheSelectedRow"] = value; }
}
and then in your click event this
protected void gvUsers_PageIndexChanging(object sender, EventArgs e)
{
TheSelectedRow = ((Control)sender).Parent as GridViewRow;
// Your code to redirect
}
I want to ask how to get a text or value of a button inside the gridview?
but i want to get the text value from this onrowcommand which use GridViewCommandEventArgs as its parameter.
as if im using onrowdatabound is (GridViewRowEventArgs), which makes it easy for me to get the button.text inside the gridview
string example = ((Button)e.Row.FindControl("btnStop")).Text;
I want to get the button.text to do an if else loop inside the onrowcommand.
Anyone know how?
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="2" CellSpacing="2" HorizontalAlign="Center" PageSize="5" Width="133%" DataKeyNames="SurveyID" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" onrowcommand="stop_survey"
onrowdatabound="filter_select" onselectedindexchanging="selected"
>
code behind
public void filter_select(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{....
((Button)e.Row.FindControl("btnStop")).Text = "Start";
}
}
public void stop_survey(object sender, GridViewCommandEventArgs e)
{
//i want to get the "btnStop" button text which is nested on the gridview.
}
i want to get the btnStop text, as I want to have different sqlstatement depending on its text (eg. Start or Stop)
the problem is i cant do e.Row inside stop_survey.
Please guide me.
Create a object of GridViewRow from refrence of command source row.
GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
But keep in mind that which type of object control is you are using to call event in above code is LinkButton. But if You Calling Rowcommand event from Simple Button then You need to Write this:
GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
After Creating Row Object You can simply find any control from Gridview using rowindex.
Label LabelEmail = (Label)GridView1.Rows[row.RowIndex].FindControl("LabelEmail");
Finally You Can Access that Properties of that Control.
LabelResult.Text = LabelEmail.Text;
Same as Above You can also find Datakeys of gridview using GridViewRow rowindex.
int code = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0].ToString());
I have a gridview add a link button "Edit":
<asp:LinkButton ID="btnViewDetails" runat="server" text="Edit" CommandName="Select"></asp:LinkButton>
and
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
using (var dataContext = new NewsStandAloneDataContext(Config.StandaloneNewsConnectionString))
{
DetailsView1.ChangeMode(DetailsViewMode.Edit);
DetailsView1.Visible = true;
var dataList =
dataContext.sp_Name(Convert.ToInt32(GridView1.SelectedValue), Value1);
ScriptManager.RegisterStartupScript(this, GetType(), "show1", "openEditWindow();", true);
DetailsView1.DataSource = dataList;
DetailsView1.DataBind();
}
}
But my details view does not show anything.
Looking at your code you have two different methods in play. In your ViewDetails button you are referencing a command name and argument. In your other block of code you are responding to the changing of the selected row. Two different concepts.
You would want to show the details view from the "ItemCommand" event, and not the selectedindexchanged event.
In the following code everytime its taking only one item from dropdownlist. When I select any other item from dropdownlist its same as first item.
Please give solution
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet _subcat = new DataSet();
_subcat = serviceus.Get_SERVICEUS_SUB_CATEGORYLIST(DropDownList1.SelectedValue.ToString());
lbsubcategory.DataSource = _subcat.Tables[0].DefaultView;
lbsubcategory.DataTextField = Convert.ToString(_subcat.Tables[0].Columns["CATEGORY_SUB1_NAME"].ColumnName);
lbsubcategory.DataBind();
Label5.Visible = true;
}
Check how you bind your dropdownlist. I think you're binding it everytime your page posts back to server. Try to use IsPostBack property of the page :
if (!IsPostBack){
DropDownList1.DataSource = datasource;
DropDownList1.DataBind();
}
Do you have:
if(!IsPostBack) {
DataBind();
}
around your initial databind (eg in OnLoad)
EnableViewState="False" on the lbsubcategory.
Assuming AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"