Adding an edit button to Gridview - asp.net

I have written a method that retrieves data from the database and returns a datatable comprising of three columns.
This datatable I am binding to a gridview control after hiding the ID field.
DataTable dt = _qbObj.getAllTags();
dvTags.DataSource = dt;
BoundField bfName = new BoundField();
bfName.DataField = dt.Columns["Name"].ToString();
bfName.HeaderText = "Name";
BoundField bfId = new BoundField();
bfId.DataField = dt.Columns["ID"].ToString();
bfId.Visible = false;
BoundField bfDesc = new BoundField();
bfDesc.DataField = dt.Columns["Description"].ToString();
bfDesc.HeaderText = "Description";
dvTags.Columns.Add(bfId);
dvTags.Columns.Add(bfName);
dvTags.Columns.Add(bfDesc);
dvTags.DataBind();
To this gridview control, I want to add an edit button, which should pop-up a jquery modal dialog box where I can enter the updated details.
I realize that I can go with a , but the problem is that I need to pop that modal dialog box without refreshing the page, and the doesn't exactly have great support for scripting.
So inside my gridview I inserted this, an Item Template.
<asp:GridView ID="dvTags" runat="server" CssClass="labs-grid-view"
AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit" OnClick="dvTagEdit" CommandName="UpdateRecord"
CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now after I am done editing the gridview doesn't update automatically, and hence I have a dedicated refresh grid button which deletes the existing "dynamically inserted columns" using this code :-
int noOfRows = dvTags.Columns.Count;
if (noOfRows > 1)
{
dvTags.Columns.RemoveAt(noOfRows - 1);
dvTags.Columns.RemoveAt(noOfRows - 2);
dvTags.Columns.RemoveAt(noOfRows - 3);
// THERE ARE A TOTAL OF **THREE** COLUMNS
}
But the problem is that after refreshing the page a couple of times, my button inside the ItemTemplate disappears and in the html is replaced with an " "
Please help me find the error. I'm thinking there is a better and easier way to achieve this. If so I'm open to them.
Thanks for reading,
Abijeet.

A few things to consider:
First, can you post your code behind for your ItemCommand event, which is rendering the modal popup and which is performing the update? It could be that your refresh after edit is not processing properly.
Second, instead of doing your databinding "inline" on your GridView, consider using the RowDataBound event within the Gridview. You can detect which row is being generated (header, data, footer) and you can properly create your edit button in there. Better yet, you can access your button from within this method and simply set the CommandArgument to your Id.
Third, when using the asp button in your GridView, it will trigger the "ItemCommand" event when clicked, which will cause a postback.
I'd recommend having a simple link in your template column, or something that you can use to trigger a jQuery modal, and you can setup a static naming convention for your items that will properly retrieve the data to put into your modal popup for editing. Then from there you should be able to process your update as normal.
I hope something in here helps.

Related

Why am I losing a DataItemTemplate control in a column when I remove all other columns in an ASPxGridView?

I have a 1 column grid. During user interaction, more columns are built and added dynamically. No matter how many columns are added or removed from the grid, the initial Print button column should always remain. Here's the grid.
<dx:ASPxGridView ID="gvAdvancedResults"
ClientInstanceName="gvAdvancedResults" runat="server" EnableRowsCache="False" KeyFieldName="ID" AutoGenerateColumns="True">
<Columns>
<dx:GridViewDataColumn Width="3%" VisibleIndex="0" Caption="Print">
<DataItemTemplate>
<dx:ASPxButton ID="btnDisplayMEC" runat="server" OnClick="btnDisplayMEC_OnClick" ClientInstanceName="btnDisplayMEC" CommandArgument='<%# Eval("ID") %>'
CssClass="reportbutt" BackColor="Transparent" Border-BorderStyle="None" Width="16" Height="16">
<Image Url="~/Assets/Images/printer.png" Width="16" Height="16"></Image>
</dx:ASPxButton>
</DataItemTemplate>
</dx:GridViewDataColumn>
</Columns>
</dx:ASPxGridView>
On a button click, I use the following to clear and repopulate the grid columns from datatable dt
'Remove all columns except the first (index 0)
For gix As Integer = gvAdvancedResults.Columns.Count - 1 To 1 Step -1
If gix <> 0 Then gvAdvancedResults.Columns.RemoveAt(gix)
Next
'Add new columns to the gridview
For Each col As DataColumn In dt.Columns
Dim xcol As Object = gvAdvancedResults.Columns(col.ColumnName)
If xcol IsNot Nothing Then Continue For
Dim newcol As New GridViewDataColumn(col.ColumnName, col.ColumnName)
gvAdvancedResults.Columns.Add(newcol)
Next
gvAdvancedResults.DataSource = dt
gvAdvancedResults.DataBind()
Now here's the problem. The "Print" column remains through the column removal process (as it should), but the ASPxButton inside the column's DataItemTemplate disappears. All the columns that are supposed to be added, are added.
Why am I losing my print button but keeping its column?
To answer your original question, it is probably due to having AutoGenerateColumns set to True. When you bind a dataSource it probably auto generates the columns at that point. You can test this by removing your code that adds the columns and I bet you will still see the columns that were in the dataSource. It might be as simple as setting AutoGenerateColumns to False.
For a few alternative ways of doing this if that doesn't work...
It would be a bit of work but you could try making the button column template in the code behind so that you can just clear and recreate all of the columns during each page load.
Or an easier method would be to use a custom command column like so...
This is c# code but it should be similar in VB:
gvAdvancedResults.Columns.Clear();
GridViewCommandColumn commandCol = new GridViewCommandColumn(" ");//Blank for no caption.
commandCol.Name = "command";
commandCol.Width = Unit.Pixel(30);
commandCol.ButtonType = GridViewCommandButtonType.Image;
gvAdvancedResults.Columns.Add(commandCol);
commandCol.VisibleIndex = 0;
GridViewCommandColumnCustomButton btnPrint = new GridViewCommandColumnCustomButton();
btnPrint.ID = "print";
btnPrint.Image.Url = "~/Assets/Images/printer.png";
btnPrint.Image.ToolTip = "Print";
commandCol.CustomButtons.Add(btnPrint );
//Then add the rest of the columns.
Then add a clientSide CustomButtonClick event to the gridView to handle the actual printing via the CustomCallback event:
<dx:ASPxGridView ID="gvAdvancedResults"
ClientInstanceName="gvAdvancedResults" runat="server"
EnableRowsCache="False"
KeyFieldName="ID"
AutoGenerateColumns="False"
OnCustomCallback="gvAdvancedResults_CustomCallback"
OR
OnCustomButtonClick="gvAdvancedResults_CustomButtonClick"
>
<ClientSideEvents CustomButtonClick="function(s, e) {
if (e.buttonID == 'print')
{
//Trigger a callbackPanel that is the parent to the gridView.
someCallbackPanel.PerformCallback(gvAdvancedResults.GetRowKey(e.visibleIndex));
//Or trigger a callback on the gridView and use GetRowKey on the server side.
gvAdvancedResults.PerformCallback('print');//Handle it on the server.
//Or some other way.
}
}" />
Or handle the server side ASPxClientGridView.CustomButtonClick Event. No example unless you really need it.
Notice that I changed AutoGenerateColumns to false since you are manually creating the columns.
Maybe if you make two gridviews, one that contain only the button column, and the other one for the rest of the data, that would surely solve the problem as you won't touch the first gridview and only bind your datas to the second gridview. Just a workaround... Not really an easy solution because you already coded the rest.

dynamic gridview in not visible / not showing

I have set a dynamic gridview, which i want to use it in another form so i created it as
public GridView gv = new GridView()
i have set in Page_Load properties of gv to
gv.AutoGenerateColumns = true;
gv.Visible = true;
then i have another grid MyGridView which is static and have data in it. So when i try to copy all static gridview data to dynamic gridview data that is
gv.DataSource = MyGridView.DataSource;
gv.DataBind();
I am not able to view the Grid gv, why is it so? someone told me to add
'Controls.Add(gv) in Page_Load
when i added its showing compile time error, that gv should be in a form with runat=server.
How can i put a dynamic gridview into a form with runat=server?
So my requirement is gv should be visible, how can i achieve this?
Thanks in advance.
you need to use some sort of holders for this try pannel
on aspx page create
<asp:Panel id="panel1" runat="server"></asp:Panel>
on your backednd
do
panel1.Controls.Add(gv)
Place a div with runat="server" into your page
then:
YourDivID.Controls.Add(gv)

Telerik RadOrgChart Node click event

I am working with Telerik Ajax control RadOrgChart
I want to capture when a node was clicked (in fact right clicked) in an OrgChart. I want the event to pass the ID of the node clicked.
I cannot find any such event in OrgChart.
Can anyone please suggest how to do it.
Thanks
Reading the documentation i see that RadOrgChart doesnt have a event handler for node click, so i think you could make your own ItemTemplate and handle the click of the items of the template, something like this.
<telerik:RadOrgChart ID="RadOrgChartDirectReports1" EnableViewState="true" Skin="Office2010Silver"
runat="server">
<ItemTemplate>
<asp:Button CausesValidation = "false" OnClick="LinkButton_Click" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeId")%>'
runat="server" Text = "Click" ID="LinkButtonNode"></asp:Button>
</ItemTemplate>
</telerik:RadOrgChart>
in this example you put a button inside a item, so, you can handle the button click.
Thanks Ewerton.
I found a better way to do it on client side instead.
Each of the telerik orgchart nodes have default css class, so something like this work:
$telerik.$(".rocItem").click(function (e) {
var orgChart = $find("<%= RadOrgChart1.ClientID %>");
var index = orgChart._extractGroupItemFromDomElement(e.target).get_index();
var hierarchicalIndex = orgChart._extractNodeFromDomElement(e.target)._getHierarchicalIndex();
hierarchicalIndex = orgChart._getRealHierarchicalIndex(hierarchicalIndex);
alert("Clicked " + hierarchicalIndex);
})

How can I pull ID from a form control in a datagrid / repeater (vb)

I have the following repeater
<asp:Repeater id="weatherFeed" Runat="server"><ItemTemplate>
<asp:LinkButton runat="server" id="PickInfo" onClick="Selection_PickInfo">
<img src="images/mapPin.png" title="<%#Container.DataItem("city")%>" />
</asp:LinkButton>
</ItemTemplate></asp:Repeater>
I'd like to call my function "Selection_PickInfo" using the Link buttons created, but I'm having the issue of not being able to actually pull information from these links.
you have a link button in the repeater that's why you are not able to use the link button functionality.you have to find the link button in the weatherFeed_ItemDataBound event then attach your
Selection_PickInfo then it will work fine.Try this .....
LinkButton pickInfo = (LinkButton)weatherFeed.FindControl("PickInfo");
pickInfo.Attributes["onclick"] = "Selection_PickInfo();";
I figured it out. In your function just do Sender.ID

asp.net Button event inside jQuery FaceBox [duplicate]

This question already has answers here:
Facebox adding commas to input
(3 answers)
Closed 3 years ago.
I'm using jQuery FaceBox to show a textbox, a dropdownlist and a button. The user can write a text in the textbox, select a value in the ddl abd hit the button. This fires some code in the codebehind. The FaceBox shows fine, and the content in it is also ok. Also, the button event is fired. This is the code for the button event handler:
protected void Button1_Click(object sender, EventArgs e)
{
_favorit = new Favoritter();
ListItem fav = ddl_favoritter.SelectedItem;
_favorit.FavoritterFolderID = int.Parse(fav.Value);
//_favorit.FavoritterFolderID = Convert.ToInt32(ddl_favoritter.SelectedItem);
_favorit.FavoritterNavn = txt_favoritNavn.Text;
_favorit.FavoritterUserID = UserID;
_favorit.FavoritterUrl = HttpContext.Current.Request.Url.ToString();
FavoritterManager.InsertFavoritter(_favorit);
}
A business object is created, and its properties set with the values read from the controls. The object is then inserted into a database, which works just fine. The problem is that the textbox and dropdown values are not set properly. The textbox value is empty, and the ddl selected value is allways 1, even though I write in the textbox, and select another ddlitem before I hit the button. The ddl is loaded like this:
if (!Page.IsPostBack)
{
_favoritter = FavoritterFolderManager.GetFavoritterFolderByUser(UserID);
ddl_favoritter.DataSource = _favoritter;
ddl_favoritter.DataBind();
}
I tried putting this code outside if (!Page.IsPostBack), and also filling it using an objectdatasource, still the same issue. It's like the controls are "reset" as I hit the button, and I don't think it has anything to do with the FaceBox, as all it does is to show the div that contains the controls... Then again, it might... Any ideas?
This is the code in the aspx page:
<div id="showme" style="display:none;">
Add to favourites.<br />
<br />
<p>
Title: <span><asp:TextBox ID="txt_favoritNavn" runat="server"></asp:TextBox></span></p>
<p>
select folder: <span><asp:DropDownList ID="ddl_favoritter" runat="server" DataTextField="FavoritterFolderNavn"
DataValueField="FavoritterFolderID" AppendDataBoundItems="true">
</asp:DropDownList>
</span>
</p>
<br />
<asp:Button ID="Button1" runat="server" Text="Gem" onclick="Button1_Click"/>
</div>
You need to have the code that fills the text box and selects the drop down item inside of the if(!IsPostBack) block, because the page load event fires again before the button event (See the ASP.NET Page Life Cycle for more info on this). Have you tried enabling view state on the control? That may be part of the issue.
Change
$('body').append($.facebox.settings.faceboxHtml)
to
$('form').append($.facebox.settings.faceboxHtml)
The problem is a lot of these controls, not just FaceBox append themselves to the body by default. jQuery UI dialog does this as well.
See this question for a fix: JQuery Facebox Plugin : Get it inside the form tag
When things happen outside the <form> tag, they're disconnected from how ASP.Net works. When you clicked submit, the values from those inputs weren't inside the form, so didn't submit to the server...which is why you aren't seeing the values.
This is the quick answer from that question, credit to Kevin Sheffield:
poking around the facebox.js I came across this line in the function init(settings)...
$('body').append($.facebox.settings.faceboxHtml)
I changed that to ...
$('#aspnetForm').append($.facebox.settings.faceboxHtml)

Resources