Optional edit in GridView's rows? - asp.net

Suppose I have a GridView on the page. GridView has edit column enabled and is showing some records. How can I enable/disable edit in rows based on other fields of data?

You can do this in a number of ways. Two of these are:
First convert the edit column to a template field.
Whatever field you want to base the enable/disable on you can add the the GridView's DataKeyNames property.
Then on the OnRowDataBound event you can do the following:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Normal)
{
var LinkButton1 = (LinkButton)e.Row.FindControl("LinkButton1");
LinkButton1.Enabled = GridView1.DataKeys[e.Row.RowIndex].Value == "SomeValue"; //Or some other logic, like converting to a boolean
}
}
Or,
In the Html markup of you aspx page, edit the linkbutton enabled property to bind the your desired field. Such as:
<asp:LinkButton ID="LinkButton1" runat="server" Text="Edit" Enabled='<%# Convert.ToBoolean(Eval("SomeField")%>'></asp:LinkButton>
Hope that helps.

Related

How to add new rows to a DataTable which is bound to a gridview in the RowDataBound event?

I have a question regarding adding new rows to a datatable which is bound to a gridview in the RowDataBound event. Do you have any idea how can I do that?
I would use the OnDataBound event on the gridview. That way after your rowdatabound is complete and your grid is data bound this event will be raised.
<asp:gridview id="Gridview1" runat="server" ondatabound="Gridview_DataBound"
...
</asp:gridview>
private void GridView_DataBound(EventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//add row to here
}
}

how to take value from grid view and stores into text box ,on a template button event?

I have created a form for saving Medium details, columns are, MID,MediumName,CreationDate,Status.I have bind full table in a gridview name gvmedium, i am having a textbox on the form .I want to fill the text box from grid views value of column MediumName on the template button click event.can any one help me?
You can use CommandName and Command Argument to achieve it and on Code Behind use RowCommand event.
<ItemTemplate>
<asp:LinkButton ID="lnkResetPassword" Text="Reset Password" runat="server" CommandName="ResetPassword" CommandArgument='<%# Bind("UserId") %>'></asp:LinkButton>
</ItemTemplate>
and then do your work here
protected void grdUserGroupList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ResetPassword")
{
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
lblMId.Text = e.CommandArgument.ToString();
txtMedium.Text=gvMedium.Rows[RowIndex ].Cells[0].Text;
}
}

Set ASP.Net GridView column to Button field programmatically

I'm generating the columns of a gridview in code which is working fine (I have AutoGenerateColumns="false" set on the page), so I don't have any columns defined in the html markup.
I would like to make one of the columns a ButtonField, so I can use a RowCommand handler in the code - is there a way to make a column a ButtonField programmatically?
ButtonField programmatic adding:
var buttonField = new ButtonField
{
ButtonType = ButtonType.Button,
Text = "My button",
CommandName = "DoSomething",
};
Grid.Columns.Add(buttonField);
Markup:
<asp:GridView runat="server" ID="Grid" AutoGenerateColumns="false" OnRowCommand="RowCommandHandler"></asp:GridView>
Handler:
protected void RowCommandHandler(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DoSomething")
{
// place code here
}
}

Why won't my LinkButton inside a GridView raise its OnClick event?

I have a LinkButton inside a GridView (via an TemplateField). No matter what I try, the LinkButton will not invoke its event handler. I have tried both:
A traditional event handler ("OnClick")
A OnRowCommand event handler at the GridView level.
In both cases, I've debugged and it doesn't even catch the event handler.
If I move the LinkButton out on the page (so it's not in the GridView), it works fine, so I know the syntax is right.
Here is the "traditional" method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" OnClick="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
What's interesting is if I remove the "CancelThis" method from the code behind, it throws an error. So I know it's aware of its event handler, because it looks for it when it compiles.
Here is the RowCommand method:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Cancel" ID="DeleteButton" CausesValidation="false" CommandName="CancelThis" runat="server" />
</ItemTemplate>
<asp:TemplateField>
In this case, the GridView has:
OnRowCommand="GridView_RowCommand"
It postsback, but never hints at raising the event.
Any idea what I'm missing here?
How are you binding your GridView? Are you using a datasource control? If you are binding manually during Page_Load, it's possible that since the grid is binding every round trip, the event handler isn't catching properly. If this is the case, you may want to try something like:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//do binding
}
}
Can you post sample binding code to go with your markup?
If you really want to force the issue, you could hook into the RowDataBound event on the Grid, find the button manually and add the handler in the code behind. Something like:
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowDataBound="gvTest_RowDataBound" />
code behind:
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find button in this row
LinkButton button = e.Row.FindControl("DeleteButton") as button;
if(button != null)
{
button.Click += new EventHandler("DeleteButton_Click");
}
}
}
protected void DeleteButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
// do as needed based on button.
}
I'm not sure what the purpose of the button is, but assuming it is a row delete button, you may not want to take this approach as in the event handler, you don't have direct access to the row in question, like you would using the RowCommand event.
Is there a reason you're using the Template field? Vs say a ButtonField? If you use a ButtonField, then you can hook into the RowCommand event.
markup snippet:
<asp:GridView ID="gvTest" runat="server" OnRowCommand="gvTest_RowCommand">
<columns>
<asp:buttonfield buttontype="Link" commandname="Delete" text="Delete"/>
....
</columns>
</asp:GridView>
code behind:
protected void gvTest_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Delete")
{
//take action as needed on this row, for example
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow currentRow = (sender as GridView).Rows[rowIndex];
//do something against the row...
}
}
You might want to consult MSDN docs on some of these topics:
RowCommandEvent
ButtonField class
EDIT:
To answer your question on the ButtonField - yes I don't see why you couldn't still deal with a buttonfield. Here's a snippet to find the buttonfield during row data bound and hide it (untested but I think would work...)
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//let's assume your buttonfield is in column 1
// (you'd know this based on your markup...)
DataControlFieldCell cell = e.Row.Cells[1] as DataControlFieldCell;
if(cell != null)
{
ButtonField field = cell.ContainingField as ButtonField;
//based on your criteria, show or hide the button
field.Visible = false;
//or
field.Visible = true;
}
}
}
Is viewstate turned on on your GridView? This has caught me out numerous times.
<button onclick="window.open('<%#Eval("ReportLinks")%>', '_blank');" title='<%#Eval("ReportLinks")%>'> Link</button>

Implementing a functional link in a Repeater control

I am implementing a Repeater in my web application to display data. I want to add functional action links in a column similar to the built-in functionality in a GridView. Can anybody give me the steps required? I assume I will add a LinkButton control to each row, somehow set the OnClick event handler to point to the same method, and somehow pass in the unique identifier on the row as a parameter.
Thanks!
I'm guessing this is what you want.
<asp:Repeater ID="rpt" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lbtn" runat="server" OnCommand="lbtn_Command"
CommandArgument='<%# DataBinder.Eval(Container.DataItem, "KeyIDColumn") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
Then in your code behind
protected void lbtn_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
}
Use LinkButtons. That way, you can handle the OnClick event in the code behind.
First you would set the onclick of the linkbutton in markup. You'll then want to implement the ItemDataBound event for the repeater.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
SomeObject obj = e.Item.DataItem as SomeObject; // w/e type of item you are bound to
var linkButton = e.Item.FindControl("linkButtonId") as LinkButton;
if(linkButton != null)
{
//either set a custom attribute or maybe append it on to the linkButton's ID
linkButton.Attributes["someUniqueId"] = obj.SomeID;
}
}
Then in the click event
void lb_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
if (lb != null)
{
// obviously do some checking to ensure the attribute isn't null
// and make it the correct datatype.
DoSomething(lb.Attributes["someUniqueId"]);
}
}

Resources