failed to call event from gridview linkbutton - c#

basically i wish to set a session folo by button click, but i failed to do so
i failed to call abcde function(), don't know what to set,i did try onRowCommand,onDataBound,OnDataBinding
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
my link button on gridview
<asp:LinkButton ID="lnkname" runat="server" Text='<%#Eval("movieTitle") %>' Width=500 CommandName="cmdLink">
in order to find link button control i did try DataGridItemEventArgs, but it didnt work as well
protected void abcde(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdLink")
{
string path = //some path;
Session["path"] = path;
((LinkButton)e.Item.FindControl("lnkname")).PostBackUrl = "~/somewhere/ + Session["path"].ToString()";
}
}
y i do so is because my next page function is depend on the session

i use gridview RowCommand
the aspx code snippet
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnLink" runat="server" CommandName="btnLinkClick"
CommandArgument='<%# Bind("roll") %>' Text="Find Name"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
the code behind snippet
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "btnLinkClick")
{
string path = //some path;
Session["path"] = path;
var button = e.CommandSource as LinkButton;
button.PostBackUrl = path;
}
}
here an interesting thing is if u set a postbackurl then second time you didn't get to server side it goes to your given url
if you simply want to set url, it is quite easy you can make a property url then bind it through button.PostBackUrl. also if u need some value from client side then set eventagument

Ok, I'm not entirely sure what you mean, however in case you're asking how to manipulate controls within the grid on databinding, it goes like this:
protected void grdvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
((LinkButton)e.Row.FindControl("lnkname")).PostBackUrl = "~/somewhere/" + Session["path"].ToString();
}
}

you need to set CommandArgument in likbutton declaration, so that you can use it for binding. GridViewRowcommandEvents
protected void abcde(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdLink")
{
string path = //some path;
Session["path"] = path;
LinkButton objButton = (LinkButton)e.Item.FindControl("lnkname"); //this is you are missing
objButton.PostBackUrl = "~/somewhere/" + Session["path"].ToString()";
}
}

Related

How to hide a link in a cell of a gridview?

I have a gridview which displays a data from the database. In one of the tables in this database have a column to store details about attanchment file. If the attachment is available that column value will set as "YES". Otherwise it will set as "NO". What I want to do is, show a link to view the attachment. But if cell value of the column is "NO" (when there is no attachment) the link must be hidden.
Note : I know how to view a file. Here what Im expecting is to hide the link in the cell which doesn't have an attachment.
This is what I have done upto now.
if (ds.Tables[0].Rows.Count > 0)
{
grdSo.DataSource = ds;
grdSo.DataBind();
for(int i=0; i <ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i][6].Equals("NO"))
{
grdSo.Rows[i].Cells[6].Visible = false;
}
else
{
grdSo.Rows[i].Cells[6].Visible = true;
}
}
}
I could hide the cell using this code. But unfortunately this hides the lines of the cell too. How can I avoid it happening?
One of the ways to do this is to use server side control like LinkButton to view the link that you want to show and set the visibility of the control as per your requirement in the OnRowDataBound event of the gridview.
Below is the code to show/hide LinkButton on OnRowDataBound event.
protected void gridId_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataSourceClass varData = (DataSourceClass)e.Row.DataItem;
// check if your data have flag to show the link
if(varData.show)
((LinkButton)e.Row.FindControl("linkbuttonId")).Visible = true;
else
((LinkButton)e.Row.FindControl("linkbuttonId")).Visible = false;
}
}
ASPX Code :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField Visible="false" DataField="id" />
<asp:TemplateField HeaderText="Has Attachment">
<ItemTemplate>
<asp:Label ID="lblAtt" runat="server" Text='<%#Eval("HasAtt") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Attachment">
<ItemTemplate>
<asp:LinkButton ID="lbtnAtt" runat="server" OnClick="lbtnAtt_Click" Visible="false">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS Code :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
//Here you write databind logic
// Datasource table of GridView1 should contain 'HasAtt' and 'id' as its binded to label.
}
private void ViewAttachment(int id)
{
//Here you write your logic to view attachment.
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow) // checking if row is datarow or not
{
Label lblHasAtt = e.Row.FindControl("lblAtt") as Label;
LinkButton lbtnViewAtt = e.Row.FindControl("lbtnAtt") as LinkButton;
lbtnViewAtt.Visible = (lblHasAtt.Text.ToLower() == "yes");
}
}
protected void lbtnAtt_Click(object sender, EventArgs e)
{
LinkButton lbtnViewAtt = sender as LinkButton;
GridViewRow grw = lbtnViewAtt.NamingContainer as GridViewRow;
int id = Convert.ToInt32(this.GridView1.Rows[grw.RowIndex].Cells[0].Text); // retriving value of first column on 'lbtnAtt' click row.
this.ViewAttachment(id);
}
I recall being able to parse through the grid view by using a for each for the rows and using a for statement for columns.
If I recall correctly, you can grab an item ie
row.Item[i]
foreach(GridViewRow row in GridView1.Rows)
{
for(int i = 0; i < GridView1.Columns.Count; i++)
{
// here you can do the logic to decide whether to show or hide the text for this cell
}
}
Sorry for formatting responding on my phone.

Text property overriden

I have a textbox and a linkbutton within the EditItemTemplate of my ListView:
<asp:TextBox ID="txt_notes" runat="server" Placeholder='<%# Eval("notes") %>'></asp:TextBox>
<asp:LinkButton ID="btn_update" class="btn btn-sm btn-success" OnClick="btn_update_Click" CommandArgument='<%# Eval("carID") %>' runat="server" >Update</asp:LinkButton>
I have this code:
protected void btn_update_Click(object sender, EventArgs e)
{
var btn_update = (LinkButton)sender;
int ID = System.Convert.ToInt32(btn_update.CommandArgument);
TextBox txt_notes = (TextBox)listview.EditItem.FindControl("txt_notes");
string notes = txt_notes.Text;
}
Now when I set a break point at string notes = txt_notes.Text it says the txt_notes.Text has nothing in it even though I have typed something in the textbox, so it seems that it is being overridden by the ItemDataBound or the PageLoad.
Does anyone know how I should overcome this problem?
It looks like you are binding your listview on page load but not checking if it is on a postback. try the below
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
listview.DataSource = your_data_source;
listview.DataBind();
}
}

Button enabling or disabling when the status for joining is true or false

I want the button "Button_Join" to be enabled when the row "join status" in my table is true and disabled when it's false.
Code:
<asp:Repeater ID="RepeaterTeam" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:Button ID="Button_Join" runat="server" Text="Join" Enabled='<%#Enabled() %>'/>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
Code behind:
protected bool Enabled()
{
if (Session["join status"] == "False")
{
return false;
}
else
{
return true;
}
}
I dont know how to do it, but that was my guess, but it doesn't seem to work.
Is this possible instead of all this code behind?
<asp:Button ID="Button_Join" runat="server" Text="Join" Enabled='<%#Eval ("join status") %>'/>
Try this with your Enabled function
Enabled='<%#Eval("Enabled")%>'
Why not do it in the button's load event?
protected void Button_Join_Load(object sender, EventArgs e)
{
// your logic...
(sender as Button).Enabled = false;
}
EDIT:
If as per your comment the button is in a repeater, use the repeater's ItemDataBound event:
protected void Your_Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem ri = e.Item;
var btn = (ri.FindControl("Button_Join") as Button);
if (btn != null) btn.Enabled =
bool.Parse((Session["join status"] ?? false).ToString()) == true ? true : false;
}
Set enabled of control in code behind.
protected void Page_Load(object sender, EventArgs e)
{
this.Button_Join.Enabled = Session["join status"] != "False";
}
UPDATE
Add handler of OnItemDataBound for your repeater
<asp:Repeater runat="server" ID="myRepeater" OnItemDataBound="myRepeater_ItemDataBound">
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Button button = (Button)e.Item.FindControl("Button_Join");
button.Enabled = Session["join status"] != "False";
}
And better put in session bool instead string. You will be able use it this way
button.Enabled = (Session["join status"] as bool?) ?? false;
I guess you might have to use Enabled='<%=Enabled() %>' instead of Enabled='<%#Enabled() %>'
<%# %> used for data binding. I see that you are not binding any data.
<%= %> is equivalent of Response.Write()
More info here...

Cancel row command does not work for GridView

i have a gridview which is inside an update panel. when i click "cance" after the edit, nothing happens. When i debug it does go into my gvWorkhours_RowCommand function and inside the cancel if, but nothing happens on screen (the edit fields are all still visible)
here is what i have:
<asp:GridView ID="gvWorkhours" runat="server" AutoGenerateColumns="false" CssClass="GridViewStyle" OnRowEditing="gvWorkhours_RowEditing"
OnRowCommand="gvWorkhours_RowCommand" >
<EmptyDataTemplate>
no data returned
</EmptyDataTemplate>
<Columns>
<asp:commandfield buttontype="Link" showeditbutton="true" edittext="Edit" />
<asp:TemplateField HeaderText="Organization">
<ItemTemplate>
<%# Eval("org.orgCode").ToString() + "- " + Eval("org.orgSubCode").ToString()%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year-Qtr">
<ItemTemplate>
<%# Eval("year").ToString() + "- " + Eval("qtr").ToString()%>
</ItemTemplate>
</asp:TemplateField>
.......
protected void gvWorkhours_RowEditing(Object sender, GridViewEditEventArgs e)
{
populateGrid(); //pulls from the Db and binds to the grid
gvWorkhours.EditIndex = e.NewEditIndex; //This is the selected row to edit
gvWorkhours.DataBind(); //Make the edit Template show up
}
protected void gvWorkhours_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Cancel")
{
gvWorkhours.EditIndex = -1;
populateGrid();
}
}
private void populateGrid()
{
//getting all variables for update here.
Workhours wh = new Workhours(selectedItem, year, qtr);
gvWorkhours.DataSource = wh.exposures;
gvWorkhours.DataBind();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
// throw(ex);
}
}
what am i missing here?
You don't have the UpdatePanel shown in your example, so I don't know how you have it set up, but if you have the UpdateMode set to Conditional, you probably need to manually call the Update method on the update panel:
if (e.CommandName == "Cancel")
{
gvWorkhours.EditIndex = -1;
populateGrid();
UpdatePanel1.Update(); // whatever the name of the UpdatePanel is
}
try to give other word than cancel like "CancelRecord" and then try with it
Yes it's an old question, but no answer.
Cancel needs to be in a RowCancelEdit method ... seems 'Cancel' is a protected word in this scenario
protected void gvResults_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView gv = (GridView)sender;
gv.EditIndex = -1;
BindGrid2();
}

Problem with a hyperlink

I put a hyperlink inside a datalist..
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server">'<%# Eval("ThreadTitle") %>'</asp:HyperLink>
<br />
<br />
</ItemTemplate>
I want it to enable it to be pressed so that the datalist event will be triggered and transfer me to another page:
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
Server.Transfer("AnswerQuestion.aspx?x=" + DataList1.DataKeyField + "&question=" + DataList1.SelectedValue + "&time=" + DateTime.Now);
}
Unfortunately, the link seems to be disabled and I cant press on it to trigger the DataList Selected event..
How can I make the hyperlink active ?
If you want to trigger a selecteditemchaned event use a LinkButton instead of hyperlink.
<asp:DataList ID="DataList1" runat="server"
onselectedindexchanged="DataList1_SelectedIndexChanged">
<ItemTemplate>
<asp:LinkButton ID="sjdj" runat="server" CommandName="Select">
<%# Container.DataItem %></asp:LinkButton>
</ItemTemplate>
</asp:DataList>
In the code behind have
protected void DataList1_SelectedIndexChanged(object sender, EventArgs e)
{
Server.Transfer("~/jjtestjj.aspx?" + DataList1.DataKeyField);
}
why arent you using the Hyperlink as a hyperlink?
You can set the NavigationURL and Text using the OnItemDataBound (or equivalent) event.
this code works with an asp:Repeater:
protected void Row_DataItem(object row, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.AlternatingItem || args.Item.ItemType == ListItemType.Item)
{
var item = (DataItemPOCO)args.Item.DataItem;
var link = (HyperLink)args.Item.FindControl("HyperLink1");
link.Text = item.LinkText;
link.NavigateUrl = item.URL;
}
}

Categories