How to edit the LinkButton visibility within a GridViewEdit in c# - c#

I wonder how to edit a the visibility of a LinkButton within a GridViewEdit:
I have got a LinkButton named "lbtnActivateConfig" in the ItemTemplate of a GridView in my aspx-File:
<ItemTemplate>
<asp:LinkButton ID="lbtnActivateConfig" runat="server"
OnClick="GridViewDeactivate" Visible="false">Deaktivieren
</asp:LinkButton>
</ItemTemplate>
Now I want to change the visibility of the LinkButton insite this method:
protected void GridViewEdit(object sender, GridViewEditEventArgs e)
{
GridViewRow row = this.ConfigGridView.Rows[e.NewEditIndex];
LinkButton buttonActivate = (LinkButton)ConfigGridView.Rows[row.RowIndex].FindControl("lbtnActivateConfig");
buttonActivate.Visible = true;
}
While debugging it catches the LinkButton an seems to set it's visibility. But the LinkButton is still invisible.
It's the same if I change the button to visible inside the aspx-File and try to change it in the method.
For me it seems that the aspx-File is always executed at last and overwrites the changes in the method. Is this right? How can I change the visibility inside the method? Any ideas?
Thank you and Goodbye!

Try the following:
protected void GridViewEdit(object sender, GridViewEditEventArgs e)
{
GridViewRow row = this.ConfigGridView.Rows[e.NewEditIndex];
(ConfigGridView.Rows[row.RowIndex].FindControl("lbtnActivateConfig")).Visible = true;
}
You don't need to cast it as LinkButton because all controls have the Visible property. And when you set FindControl to a variable, the variable is set by value rather than by reference which means you aren't referring to the actual control.

Related

How to make RadioButtons work in a Listview

I want to make RadioButtons work in a ListView. I added a RadioButton control in the ListView and wrapped it with a LinkButton control. I used the LinkButton in order to use the ItemCommand property of the the ListView to change the state of the RadioButton from code Behind.
<td>
<asp:LinkButton ID="LinkButton6" runat="server" CommandName="Driver">
<asp:RadioButton ID="SelectedDriver" runat="server" AutoPostBack="true" OnCheckedChanged="SelectedDriver_CheckedChanged" />
</asp:LinkButton></td>
To be able to make all radioButton mutually exclusive, I reset all radioButtons in the ListView to false then I set the RadioButton that call the event to true
Here is the method from code behind:
protected void Drivers_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName.ToString() == "Driver")
{
foreach (ListViewItem listItem in this.Drivers.Items)
{
(listItem.FindControl("SelectedDriver") as RadioButton).Checked = false;
}
(e.Item.FindControl("SelectedDriver") as RadioButton).Checked = true;
}
}
However it doesn't work as I wanted. when I click on the radioButtons, they keep getting selected none of them get reset. For it to work, I have to add some text beside the radioButton control and I have to click on the text not on the RadioButton for it to work. As you can see the text part is pretty annoying.
Can anyone help me to know what i can do for it to work as intended? Or Does anyone knows a solution that can work.
Thanks
For the RadioButtons to work as expected, I set the AutoPostBack = "true" the property OnCheckedChanged = "SelectedDriver_CheckedChanged"
from code behind I did the following and everything works perfectly
protected void SelectedDriver_CheckedChanged(object sender, EventArgs e)
{
RadioButton selectedButton = new RadioButton();
selectedButton = (RadioButton)sender;
foreach (ListViewItem listItem in this.Drivers.Items)
{
(listItem.FindControl("SelectedDriver") as RadioButton).Checked = false;
}
selectedButton.Checked = true;
}

Attaching a click event onto an image within a grid view

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.

Gridview on Linkbutton click, Pass complete GridRow information to the next page? What are best ways to do this?

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
}

asp.net gridview onrowcommand -->( GridViewCommandEventArgs)

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

Visible Checkbox only on Gridview's last row?

Is it possible to have a Checkbox that only shows up when Editing the last row of a GridView?
I have tried something like this in the EditItemTemplate:
<asp:CheckBox ID="chkNextDay" runat="server"
ToolTip="Is it a next-day departure?"
Enabled="true"
Checked='<%# DateTime.Parse(Eval("OutHour","{0:d}")).Date >
DateTime.Parse(Eval("InHour","{0:d}")).Date %>'/>
Then on code-behind I tried hiding it for rows other than the last one like this:
protected void grvOutHour_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView grvOutHour = (GridView)this.grvReport.Rows[grvReport.EditIndex].FindControl("grvOutHour");
TextBox txtBox = (TextBox)grvOutHour.Rows[e.NewEditIndex].FindControl("txtEditOutHour");
CheckBox nextDay = (CheckBox)grvOutHour.Rows[e.NewEditIndex].FindControl("chkNextDay");
if (grvOutHour.Rows.Count-1 != e.NewEditIndex)
nextDay.Visible = false;
}
This ALMOST worked, but the checkbox kept showing for all fields, I think because the RowDataBound is called AFTER RowEditing again so it renders the whole thing again :(
Any suggestions?
Thanks,
EtonB.
Use RowDataBound instead...
protected void grvOutHour_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
GridView grid = (GridView)sender;
CheckBox nextDay = (CheckBox)e.Row.FindControl("chkNextDay");
nextDay.Visible = (e.Row.RowIndex == (grid.Rows.Count - 1));
}
}
You will need to handle hiding the checkbox in the RowDataBound event.
You'll need to determine what the last row is, and set the checkboxes visible property to true when that condition is true, obviously.
I guess it's more of a hack than an elegant solution, but I would probably just hide the other checkboxes via JavaScript if the condition is true.

Categories