Set ASP.Net GridView column to Button field programmatically - asp.net

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
}
}

Related

AspxGridView checkbox checked column value

I am using one aspxGridview where I used checkbox. Now I need when I check any of the row particular column value I should get in server side to complete my business logic.
Below is the gridview used:
<dx:ASPxGridView KeyFieldName="PracticeID" ID="ASPxGrd" runat="server" ClientInstanceName="grid"
ClientIDMode="AutoID" AutoGenerateColumns="false" Width="100%" OnSelectionChanged="ASPxGrd_SelectionChanged">
<Columns>
<dx:GridViewDataColumn VisibleIndex="0" Name="CheckBoxColumn">
<DataItemTemplate>
<dx:ASPxCheckBox ID="ASPxCheckBox1" runat="server" OnCheckedChanged="ASPxCheckBox1_CheckedChanged" AutoPostBack="true">
</dx:ASPxCheckBox>
</DataItemTemplate>
</dx:GridViewDataColumn>
<dx:GridViewDataColumn FieldName="PracticeName" Caption="Description" VisibleIndex="1">
<FooterTemplate>
Total:
</FooterTemplate>
</dx:GridViewDataColumn>
</dx:ASPxGridView>
I have tried to use oncheckedevent in checkbox with auto postback true and used code to get selected row like below:
protected void ASPxCheckBox1_CheckedChanged(object sender, EventArgs e)
{
ASPxGridView grid = sender as ASPxGridView;
string currentMasterKey = Convert.ToString(grid.GetMasterRowKeyValue());
}
but getting null value of grid object.
Need help.
In your example you have used DataItemTemplate, so in that case the sender will be the control which is added in that data template i.e ASPxCheckBox and you are casting it to grid bcoz of that it is getting null.
try out below snippet.
protected void ASPxCheckBox1_CheckedChanged(object sender, EventArgs e)
{
ASPxCheckBox checkBox = sender as ASPxCheckBox;
var grid = (checkBox.NamingContainer as DevExpress.Web.ASPxGridView.GridViewDataItemTemplateContainer).Grid;
string currentMasterKey = Convert.ToString(grid.GetMasterRowKeyValue());
}
I found this answer before and it's working fine like below:
for (int i = 0; i < ASPxGrd.VisibleRowCount; i++)
{
ASPxCheckBox chk = ASPxGrd.FindRowCellTemplateControl(i, null, "ASPxCheckBox1") as ASPxCheckBox;
if (chk.Checked)
{
if (i == 0)
{
practiceName = ASPxGrd.GetRowValues(i, "PracticeName").ToString();
}
}
}
using this code i am able to get selected checkbox column value.

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;
}
}

Making entire row in Gridview clickable

I've been trying to follow this answer: How to implement full row selecting in GridView without select button?
But I'm still slightly confused. After following that question, my rows are now clickable. But how do I implement it to do something after being clicked? Currently, I use a button to do what I need to the database per row:
Here is the .aspx code:
<Columns>
<asp:ButtonField Text = "Click Me" CommandName = "Clicked" ButtonType = "Button" />
...other columns stuff
</Columns>
C# code behind:
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
//if button is clicked
if (e.CommandName == "Clicked")
{
//go find the index on the gridview
int selectedIndex = MsgInbox.SelectedIndex;
if (int.TryParse(e.CommandArgument.ToString(), out selectedIndex))
{
//do something with database
}
Now that works beautifully. However, I don't want a button to be clickable, I want a entire row to be clickable. I know this is currently wrong, but this is what I have so far for the code:
.aspx code
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="SelectRow" runat="server" ForeColor="red" CommandName="Clicked"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void Gridview_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
var selectButton = e.Row.FindControl("SelectRow") as Button;
e.Row.Attributes["onclick"] = ClientScript.GetPostBackEventReference(selectButton, "");
I get a simple null pointer exception when I do this, but I'm not really familiar with e.Row.Attributes so I really have no idea where this is failing and what I need to do to add the database logic.
Thanks
It would be a lot simpler if you are ready to use jquery. For example,
<asp:GridView rowStyle-CssClass="row" ...
...
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="SelectRow" runat="server" CommandName="Clicked" CssClass="selButton" />
</ItemTemplate>
</asp:TemplateField>
Note that each data row will have css class row and select button will have selButton
CSS would be some-thing like
tr.row { } /* normal row styling */
tr.row-highlight { background-color: blue; } /* highlighted row styling */
tr.row .selButton { display:none; visibility:hidden; } /* select button styling, I am using hidden button */
Finally the java-script
$(document).ready(function() {
$('tr.row').click(
function() {
// simulate click of select button
$(this).find('.selButton').click();
}).hover(
// add/remove css class to highlight on mouse over/out
function() { $(this).addClass('row-highlight'); },
function() { $(this).removeClass('row-highlight'); });
});
So I figured it out, and I'm sure there are better ways to implement it via jquery or javascript but I am not too good at either yet.
For my .aspx file, for the gridview, I simply added:
AutoGenerateSelectButton ="true"
In my C#, under MsgInbox_SelectedIndexChanged, I put all my RowCommand logic.
Finally, in C#, under my Gridview_RowCreated, I added this line to hide the Select link:
e.Row.Cells[0].Style["display"] = "none";

Optional edit in GridView's rows?

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.

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>

Resources