I used the following
ondblClickRow: function(){
var row_id = $("#grid").getGridParam('selrow');
jQuery('#grid').editRow(row_id, true);
}
from:
jqGrid Cell Editing - Double Click to Edit?
On double clicking I am able to get the alert but the EditRow function simply doesn't work.
-------Update-----------
This is the following code I use onclient side:-
function setJqGridParameters(parsedResult) {
var lastSel;
$('#list').jqGrid('GridUnload');
$("#list").jqGrid({
colModel: JSON.parse(parsedResult.colModel),
colNames: JSON.parse(parsedResult.col),
datatype: "jsonstring",
datastr: JSON.parse(parsedResult.rows),
jsonReader: {
repeatitems: false
},
gridview: true,
rowNum: 10,
cmTemplate: { title: false }, //, sortable: false },
viewrecords: false,
loadonce: true,
loadui: 'block',
height: 'auto',
autowidth: true,
loadtext: "Loading....",
pgbuttons: false,
pginput: false,
pgtext: "",
shrinkToFit: false,
hoverrows: false,
ondblClickRow: function (rowid) {
if (rowid && rowid !== lastSel) {
$('#list').restoreRow(lastSel);
lastSel = rowid;
}
$(this).jqGrid("editGridRow", rowid, {
keys: true,
addCaption: "Add Record",
editCaption: "Edit Record",
bSubmit: "Submit",
bCancel: "Cancel",
bClose: "Close",
saveData: "Data has been changed! Save changes?",
bYes: "Yes",
bNo: "No",
bExit: "Cancel",
width: window.screen.width / 3,
top: window.screen.height / 4,
left: window.screen.availWidth / 3,
editUrl: 'TypicalVolume.aspx/UpdateVolumeData',
beforeSubmit: function (postData, formid) {
//alert(JSON.stringify(postData));
PostDataToServer(postData);
$(".ui-widget-overlay").trigger('click');
$('#list').trigger('reloadGrid');
return false;
},
afterShowForm: function (formid) {
$("#COl1").focus();
//var cm = $(this).jqGrid('getColProp', 'Specialty');
//debugger;
}
});
// debugger;
// var grid = $('#list');
// var myRowData = grid.getRowData(rowid);
// grid.editRow(rowid, true);
//alert(myRowData['Specialty'] + ' ' + myRowData['SpecialtyName']);
},
loadComplete: function () {
fixPositionsOfFrozenDivs.call(this);
},
onSortCol: function (index, icol, sortorder) {
sortColumns(index, icol, sortorder);
return 'stop';
}
});
resizeColumnHeader.call($("#list")[0]);
$("#list").parents('div.ui-jqgrid-bdiv').css("max-height", $(window).height() - $('#pivotGridDiv').offset().top - 60);
$("#list").jqGrid('setFrozenColumns');
$("#list").triggerHandler("jqGridAfterGridComplete");
fixPositionsOfFrozenDivs.call($("#list")[0]);
$(".s-ico").hide();
var cm = $("#list")[0].p.colModel;
$.each($("#list")[0].grid.headers, function (index, value) {
var cmi = cm[index], colName = cmi.name;
if (cmi.sortable) {
$('div.ui-jqgrid-sortable', value.el).css({ cursor: "pointer" });
}
});
}
function PostDataToServer(Data) {
$.ajax({
type: "POST",
data: "{" + "Data" + ":" + JSON.stringify(Data) + "}",
url: "TypicalVolume.aspx/UpdateVolumeData",
//data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.d == "null") {
RedirectToLogin();
}
else {
SetValues(result);
}
},
error: function (result) {
$('#loadingIndicator').hide();
alert("getPageLoadData: " + result.responseText);
//RedirectToErrorPage();
}
});
}
The SetJqGridParameters() function is called on pageload which sets all parameters of Jqgrid. I used the PostDataToServer() function to send data to server and write the Db Changes. Note:- If I remove the functionality I get an error of null reference in jqgrid.min.js.
----Server Code----
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string UpdateVolumeData(object Data)
{
string WhereCondition1 = "",WhereCondition2="";
List<string> UpdateStatements = new List<string>();
Dictionary<string, string> data = new Dictionary<string, string>();
data = ToDictionary(Data);
foreach(KeyValuePair<string,string> entry in data)
{
if (entry.Key.ToString() == "MainCol1")
{
if (WhereCondition1 == "")
{
WhereCondition1 = WhereCondition1 + entry.Key.ToString() + "=" +"'"+ entry.Value.ToString()+"'";
}
else
{
WhereCondition1 = WhereCondition1 + "," + entry.Key.ToString() + "=" + "'"+entry.Value.ToString()+"'";
}
}
else if (entry.Key.ToString() == "MainCol2")
{
if (WhereCondition2 == "")
{
WhereCondition2 = WhereCondition2 + entry.Key.ToString() + "=" +"'"+ entry.Value.ToString()+"'";
}
else
{
WhereCondition2 = WhereCondition2 + "," + entry.Key.ToString() + "=" +"'"+ entry.Value.ToString()+"'";
}
}
}
foreach (KeyValuePair<string, string> entry in data)
{
if (entry.Key.ToString() != "MainCol1" && entry.Key.ToString() != "MainCol2")
{
UpdateStatements.Add("Update TypicalVolume set TypicalVolume = " + entry.Value + " where Modality = '" + entry.Key + "' and " + WhereCondition1 + " and " + WhereCondition2);
}
}
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//var data = serializer.Serialize(Data);
string sqlstatements = string.Join(" ", UpdateStatements);
SqlConnection conn = new SqlConnection(sqlConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand(sqlstatements, conn);
cmd.ExecuteNonQuery();
conn.Close();
GridData gd = new GridData();
gd = GetGridData();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(gd);
}
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetDataBySearchCriteria()
{
try
{
HttpContext.Current.Session["RoleID"] = 4;
if (HttpContext.Current.Session["RoleID"] != null)
{
if (!CheckAuthorization()) // Redirect to error page if not authorized
{
throw new Exception("Un Authorized Acess");
}
else
{
HttpContext.Current.Session["TypicalVolumeSession"] = null;
if (HttpContext.Current.Session["TypicalVolumeSession"] != null)
{
GridData gd = new GridData();
gd = HttpContext.Current.Session["TypicalVolumeSession"] as GridData;
JavaScriptSerializer serializer = new JavaScriptSerializer();
GridData gd1 = GetGridData();
return serializer.Serialize(gd1);
}
else
{
HttpContext.Current.Session["TypicalVolumeSession"] = null;
GridData gridData = new GridData();
DataSet ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.StoredProcedure, "GetTypicalVolumes");
DataTable Datadt = ds.Tables[0];
//create col model for jqgrid
StringBuilder sbcol = new StringBuilder();
sbcol.Append("[");
foreach (DataColumn column in Datadt.Columns)
{
sbcol.Append("\"").Append(column.ColumnName).Append("\",");
}
sbcol.Remove(sbcol.Length - 1, 1).Append("]");
StringBuilder sbcolModel = new StringBuilder();
sbcolModel.Append("[");
string[] rowAreaFields = "MainCol1,MainCol2".Split(',');
//create rowdata for jqgrid
foreach (DataColumn column in Datadt.Columns)
{
if (rowAreaFields.Contains(column.ColumnName.Trim()))//apply style for row area fields
{
sbcolModel.Append("{\"name\":\"").Append(column.ColumnName.Trim()).Append("\",\"index\":\"").Append(column.ColumnName.Trim()).Append("\",\"classes\":\"colstyle\",\"align\":\"left\",\"editable\":true,\"editoptions\": { \"disabled\": \"disabled\" },\"sortable\":true,\"frozen\":true},");
}
else
{
sbcolModel.Append("{\"name\":\"").Append(column.ColumnName.Trim()).Append("\",\"index\":\"").Append(column.ColumnName.Trim()).Append("\",\"align\":\"right\",\"sortable\":false,\"editable\":true,\"width\":\"60px\"},");
}
}
sbcolModel.Remove(sbcolModel.Length - 1, 1);
sbcolModel.Append("]");
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> drow;
foreach (DataRow dr in Datadt.Rows)
{
drow = new Dictionary<string, object>();
foreach (DataColumn col in Datadt.Columns)
{
drow.Add(col.ColumnName, dr[col]);
}
rows.Add(drow);
}
StringBuilder sbjsonRows = new StringBuilder();
sbjsonRows.Append(serializer.Serialize(rows));
StringBuilder json = new StringBuilder();
json.Append("{").Append("\"rows\":").Append(sbjsonRows.ToString().Trim()).Append("}");
json.ToString();
gridData.col = sbcol.ToString();
gridData.colModel = sbcolModel.ToString();
gridData.rows = sbjsonRows.ToString().Trim();
return serializer.Serialize(gridData);//serialize and return to ajax method
}
}
}
else
{
return "null";//if session expired
}
}
catch (Exception ex)
{
LogError(ex);
throw;
}
}
The code is in testing mode its still under development, the code is a template from other pages I have developed so it has used session but its not actually required as of now.
Requirement:- I have lots of data. So I would like to update the db and show the real data from db. Because other users might have updated it. So If possible I might want to load data in a lazy manner where I could load data for say 3 pages and then continue loading in the background(do I have such an option in jqgrid). In case its not feasible loading the whole data is ok.
Also I wish to make examples in C# and contribute them for other new users in as many ways as possible.So that users can find all documentation and help in one place. Please suggest how can I do that too.
For those who refer this:- This question originally started for editable rows. The first suggestion I got from @Oleg was sufficient. Later he found that my code was inconsistent because we used code from different jqgrid and also the server code was non standard (do not use those techniques).
To Beginners using jqgrid
Please make sure you are using the same jqgrid through out which will help you keep your code consistent. On the internet you can find different versions of jqgrid, so first make sure whether you want to you use free or commercial version, then go for the latest.