DataTable not rendring Gridview after button click event - c#

In my page when it's creating, everything is working fine but when I am clicking on the button to show the selected row, then my grid view is not rendering as a datatable. What I need to do to fix this or what I am doing wrong?
My script:
<script type="text/javascript">
$(function () {
$('[id*=gvTest]').prepend($("<thead></thead>").append($(this).find("tr:first"))).DataTable({
"responsive": true,
"sPaginationType": "full_numbers",
});
});
$(document).ready(function () {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
});
$('#btnRead').click(function () {
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0]
});
});
} );
</script>
My Grid:
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="PatientID" HeaderText="Patient ID" >
</asp:BoundField>
<asp:BoundField DataField="PatientName" HeaderText="PatientName" >
</asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="Age" >
</asp:BoundField>
<asp:BoundField HeaderText="Sex" DataField="Sex" >
</asp:BoundField>
<asp:BoundField HeaderText="Mod" DataField="Modality" >
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
When my page is created:
Everything is working fine, but when I click a button then this happens:
What do I need to do now to fix this problem ?

The UpdatePanel refreshes the DOM, so any changes made to it with jQuery are lost. You need to call DataTable() again after an Async PostBack. You can use the PageRequestManager for that.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
createDataTable();
});
createDataTable();
function createDataTable() {
var table = $('#gvTest').DataTable();
$('#gvTest tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
});
}
</script>

The best way to fix this issue is by implementing this in pageLoad function.
In this case I used a Gridview:
function pageLoad() {
$("<thead></thead>").append($("#grvPast tr:first")).prependTo($("#grvPast"));
$('#grvPast').dataTable();
}

after using a lots of others code i did'nt get a proper solution so i used this on my page load and its working fine
gvTest.UseAccessibleHeader = true;
//adds <thead> and <tbody> elements
gvTest.HeaderRow.TableSection =
TableRowSection.TableHeader;

Related

How can chage the row index of gridView using C#

I have a gridView which is movable with dragAndDrop. But i am able only for move the row of gridView using dragAndDrop. This is my code:
gridView1.datasource = dt;
gridView1.dataBind();
<asp:GridView ID="GridView3" CellPadding="5" CellSpacing="0"
OnRowDataBound="GridView3_RowDataBound"
ForeColor="#333" runat="server"
AutoGenerateColumns="true">
</asp:GridView>
<asp:Button ID="Save" runat="server" Text="Save" onclick="btnsave_Click" />
// use of JQuery for dragAndDrop
$(function () {
$("[id*=GridView1]").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'pointer',
axis: 'y',
dropOnEmpty: false,
start: function (e, ui) {
ui.item.addClass("selected");
},
stop: function (e, ui) {
ui.item.removeClass("selected");
},
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
});
Using this code, i am only able to move rows of gridView. But i want, when i will click on save button then the order of rows which are changed by dragAndDrop will be shown. thanks.

How to get click event in code behind in c# using jquery

Hi Please check i want to get click event in code behind as i am using master page concept and i have one child form of it in this page i have ContentPlaceHolder, My button "btnSubmit" this is a linkbutton which is under GridView. i want loading image when i will click on btnSubmit button. please check and help.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
$('form').live("submit", function () {
ShowProgress();
});
aspx page..
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Journal" HeaderText="Customer Id" />
<asp:BoundField DataField="ISBN" HeaderText="Contact Name" />
<asp:BoundField DataField="Status" HeaderText="City" />
<asp:TemplateField HeaderText="Btn">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Load Customers"
OnClick="btnSubmit_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="loading" align="center">
Downloading Files. Please wait<br />
<br />
<img src="loader.gif" alt="" />
</div>
</asp:Content>
In cs Page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string script = "$(document).ready(function () { $('[id*=btnSubmit]').click(); });";
ClientScript.RegisterStartupScript(this.GetType(), "load", script, true);
}
}
try this way
Script AS
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
$('form').live("submit", function () {
ShowProgress();
});
</script>
And Add event onrowdatabound in grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
And CS page
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Button btnSubmit = e.Row.FindControl("btnSubmit") as Button;
btnSubmit.Attributes.Add("OnClick", "ShowProgress();");
}
}
Use OnClientClick event of the button also in this event call a javascript function which change the css of the progress bar to visible.
OnClientClick="ShowProgress();return true;"

how to get datakey value when row double click radgrid

i am using the following code to get datakey value when row double click, now i want to use this key value in serverside, how can i get this value there(or) how to pass this value to server side?
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function RadGrid1_RowDblClick(sender, args) {
var keyValue = dataItem.getDataKeyValue('WageID');
// want to get this keyvalue in server side
}
</script>
</telerik:RadScriptBlock>
<telerik:RadGrid ID="RadGrid1" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView ClientDataKeyNames="ID">
</MasterTableView>
<ClientSettings>
<ClientEvents OnRowDblClick="RadGrid1_RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
Finally i got the answer for this question, following is the answer
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function RadGrid1_RowDblClick(sender, args) {
//changed code here
var grid = $find("<%= RadGrid1.ClientID %>");
var MasterTable = grid.get_masterTableView();
var row = MasterTable.get_dataItems()[eventArgs.get_itemIndexHierarchical()];
var key = MasterTable.getCellByColumnUniqueName(row, "WageID"); // get the value by uniquecolumnname
var ID = key.innerHTML;
MasterTable.fireCommand("MyClick2",ID);
}
</script>
</telerik:RadScriptBlock>
<telerik:RadGrid ID="RadGrid1" runat="server"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView ClientDataKeyNames="ID">
</MasterTableView>
<ClientSettings>
<ClientEvents OnRowDblClick="RadGrid1_RowDblClick" />
</ClientSettings>
</telerik:RadGrid>
//add this code under itemcommand event of radgrid.
if (e.CommandName == "MyClick2")
{
object obj = e.CommandArgument;
string ID = obj.ToString();
//logic to fulfill our requirment.
}
Here might solve your problem
http://demos.telerik.com/aspnet-ajax/grid/examples/overview/defaultcs.aspx
You can get the datakeyvalue on client side using the following code:
function OnRowDblClick(sender, args) {
var key= args.getDataKeyValue("WageID");
document.getElementById('<%= HidenField1.ClientID %>').value = key;
}
To pass these value to server side one suggestion is you can assign this to a hiddenfield and access that hiddenfield in server side.

How to use jquery modal dialogs for Edit and Display record?

1) If i click the view button from the grid, it has to display jquery dialog for that particular LID, but it is not working.(In the dialog, it has to show only REMARKS1 column text)
2) I have included the linkbutton(Cancel/Edit) through c# code to edit the particular row.
How can i use jquery dialog for edit/Cancel.
I have pasted my aspx webpage and C# code.It would be great if you can change this code, otherwise please provide new code.
Please find the attached image, it will show you grid and dialog box.
aspx page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="jquery/themes/dark-hive/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jquery/jquery-1.9.0.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.core.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.widget.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.position.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.button.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.dialog.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect-slide.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect-explode.js" type="text/javascript"></script>
<script src="jquery/ui/jquery.ui.effect-fade.js" type="text/javascript"></script>
<link href="jquery/themes/demos.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#example1").dialog({
modal: true,
autoOpen: false,
show: {
effect: "slide",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
$('#btuser').click(function (event) {
event.preventDefault();
$('#example1').dialog('open');
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 500px;">
<asp:GridView ID="grdDisplay" runat="server" AutoGenerateColumns="False" CellPadding="1"
CellSpacing="1" Height="0px" GridLines="None" CssClass="myGrid" PagerStyle-CssClass="pager"
AlternatingRowStyle-CssClass="alt" Width="1024px" RowStyle-CssClass="RowStyle"
Font-Bold="False" Font-Names="Segoe UI" Font-Size="13px" OnRowDataBound="grdDisplay_RowDataBound">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:BoundField HeaderText="LID" DataField="l_ID" ItemStyle-Width="45px" />
<asp:BoundField HeaderText="S_Date" DataField="s_date" DataFormatString="{0:dd-MM-yyyy}" ItemStyle-Width="60px" />
<asp:BoundField HeaderText="E_Date" DataField="e_date" DataFormatString="{0:dd-MM-yyyy}" ItemStyle-Width="60px" />
<asp:BoundField HeaderText="Div" DataField="Div_type" />
<asp:TemplateField HeaderText="Remarks1" ItemStyle-Width="125px" ItemStyle-Height="25px">
<ItemTemplate>
<asp:TextBox runat="server" ID="lblreason" Text='<%# Bind("Remarks1") %>' Height="20" Width="90" ReadOnly="true" CssClass="cmdtextbox">
</asp:TextBox>
<div style="margin-top: 0px; float: right;">
<asp:Button runat="server" Width="25" Height="25" ID="btuser" CssClass="btreason" text="View" />
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Remarks2" DataField="Remarks2" ItemStyle-Width="62px" />
</asp:TemplateField>
<asp:BoundField HeaderText="Remarks3" DataField="Remarks3" ItemStyle-Width="60px" />
</Columns>
<PagerStyle CssClass="pager"></PagerStyle>
<RowStyle CssClass="RowStyle" />
</asp:GridView>
</div>
</form>
</body>
</html>
C# code*
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtmydata = new DataTable();
if (!Page.IsPostBack)
{
dtmydata = Dtthandler.GetEmData(HttpContext.Current.Session["TatID"].ToString());
//Add new column
dtmydata.Columns.Add(new DataColumn("User Action", Type.GetType("System.String")));
foreach (DataRow row in dtmydata.Rows)
{
currentdate = DateTime.Now;
Edate = Convert.ToDateTime(row[2].ToString());
strtmpCdate = currentdate.ToShortDateString();
strtmpEdate = Edate.ToShortDateString();
if (Convert.ToDateTime(strtmpCdate) <= Convert.ToDateTime(strtmpEdate))
{
row[7] = "Yes";
}
else
{
row[7] = "No";
}
//Bind data to grid
grdDisplay.DataSource = dtmydata;
grdDisplay.DataBind();
}
}
}
protected void grdDisplay_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkbtnCancel = new LinkButton();
LinkButton lnkbtnModify = new LinkButton();
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[7].Text == "Yes")
{
lnkbtnCancel.Text = "Cancel";
lnkbtnModify.Text = "Modify";
e.Row.Cells[7].Controls.Add(lnkbtnCancel);
e.Row.Cells[7].Controls.Add(lnkbtnModify);
//How to populate jquery dialog using this linkbutton?
}
else
{
e.Row.Cells[7].Text = string.Empty;
}
}
}
catch (Exception ex)
{
}
}
this is an example from my code - please adjust to your use:
have dialog declared like so:
<div id="dialog-form">
... // all of the elements you need in the dialog
</div>
and then in the javascript section:
$("#dialog-form").dialog({
autoOpen: false,
height: 580,
width: 800,
modal: true,
buttons: {
"Do Something": function () {
},
Cancel: function () {
$(this).dialog("close");
}
}
});
finally - on the button or element used to fire up your dialog:
onclick='$( "#dialog-form" ).dialog( "open" );'
I hope this helps.

Check all CheckBoxes in GridView

I have a GridView in ASP.NET/C# with a CheckBoxField, a BoundField and 2 ButtonFields. All 4 of them has a header to make clear where the column stands for. At the Page_Load event I set the ВataЫource of the GridView to my filled DataTable.
I want to make it easier to use for the user, and want to make a checkbox in the header. When that checkbox is checked by the user, all CheckBoxes should be checked in the GridView. I have set the HeaderText of the CheckBoxField to <input type='checkbox' />, and it shows a checkbox in the header now.
Now I want to add a function to that checkbox, that when it's checked, all CheckBoxes will be checked en vice versa. I tried to do it with jQuery, but it didn't work because I can't find a way to give all the CheckBoxes in the GridView the same ID or NAME.
Is there a event that occurs when I check the HTML based checkbox within the header? If yes, which event?
If no, how can i trigger a event when I check that checkbox, and change the GridView from my code-behind.
And if none of that is possible, how can i do it on another way, with javascript, jQuery or maybe with a ASP.net control.
I hope you can help me with this, but please don't expect i'm a code guru. I'm a intern at a company where the need a system, with this functionality.
Update:
Thank you everyone for helping me out. What is the easiest way to get the DataSource back into the DataTable, because i need to know which rows were selected and which were not?
Using jQuery, you get all the check boxes inside the GridView, and then for each one you change the status as you like. You call this javascript function from onclick of a link or a button, or what ever you like.
function CheckAll()
{
var updateButtons = jQuery('#<%=gvGridViewId.ClientID%> input[type=checkbox]');
updateButtons.each( function() {
// use this line to change the status if check to uncheck and vice versa
// or make it as you like with similar function
jQuery(this).attr("checked", !this.checked);
});
}
try this code according to you
in grid view
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="headerchkbox" runat="server" CssClass="chkheader" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxAssign" runat="server" CssClass="chkitems" />
</ItemTemplate>
</asp:TemplateField>
java script
<script type="text/javascript">
$(window).bind('load', function () {
var headerChk = $(".chkheader input");
var itemChk = $(".chkitems input");
headerChk.bind("click", function () { itemChk.each(function () { this.checked = headerChk[0].checked; })
});
itemChk.bind("click", function () { if ($(this).checked == false) headerChk[0].checked = false; });
});
</script>
Here is a sample I have put together for you.
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).live('click', function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).live('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lstObjects = new List<string> { "aaa", "bbb" };
GridView1.DataSource = lstObjects;
GridView1.DataBind();
}
}
If you are using the latest version of jQuery (1.7)
Use the following:
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).click(function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).click(ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>

Categories

Resources