2013-12-20 226 views
0

即時通訊目前堆棧如何顯示我的數據庫中的所有數據連接上的jqGrid使用jqGrid的即時通訊新的,我不知道爲什麼我的數據不顯示,當我使用本地主機與MYSQL及ASP.NET

部署於Web

getdata.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Configuration; 
using System.Web.Services; 
using System.Web.Script.Services; 
using MySql.Data.MySqlClient; 


public partial class getdata : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
    public struct s_GridResult 
    { 
     public int page; 
     public int total; 
     public int record; 
     public s_RowData[] rows; 

    } 
    public struct s_RowData 
    { 
     public int id; 
     public string[] cell; 
    } 
    [WebMethod] 
    public static s_GridResult GetDataTable(string _search, string nd, int rows, int page, 
string sidx, string sord) 
    { 

     int startindex = (page - 1); 
     int endindex = page; 
     string sql = "SELECT ItemCode,PartNumber FROM tblitemcodefromqne"; 

     DataTable dt = new DataTable(); 
     MySqlConnection conn = new 
MySqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString); 
     MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn); 
     adapter.Fill(dt); 
     s_GridResult result = new s_GridResult(); 
     List<s_RowData> rowsadded = new List<s_RowData>(); 
     int idx = 1; 
     foreach (DataRow row in dt.Rows) 
     { 
      s_RowData newrow = new s_RowData(); 
      newrow.id = idx++; 
      newrow.cell = new string[2]; //total number of columns 
      newrow.cell[0] = row[0].ToString(); 
      newrow.cell[1] = row[1].ToString(); 
      rowsadded.Add(newrow); 
     } 
     result.rows = rowsadded.ToArray(); 
     result.page = page; 
     result.total = dt.Rows.Count; 
     result.record = rowsadded.Count; 
     return result; 
    } 


} 

getdata.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 
/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
    <title></title> 
    <link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/jquery- 
ui-1.9.2.custom.css" /> 
    <link rel="Stylesheet" type="text/css" media="screen" href="JQGridReq/ui.jqgrid.css" /> 
    <link rel="Stylesheet" type="text/css" media="screen" href="Themes/style.css" /> 


    <script type="text/javascript" src="JQGridReq/jquery-1.9.0.min.js"></script> 
    <script type="text/javascript" src="JQGridReq/jquery.json-2.2.min.js"></script> 
    <script type="text/javascript" src="JQGridReq/jquery-ui-1.9.4.custom.min.js"></script> 
    <script type="text/javascript" src="JQGridReq/grid.locale-en.js"></script> 
    <script type="text/javascript" src="JQGridReq/jquery.jqGrid.js"></script> 




     <script type="text/javascript" > 
      $(document).ready(function() { 
       $.extend($.jgrid.defaults, 
        { datatype: 'json' }, 
        { ajaxGridOptions: { contentType: "application/json", 
         success: function (data, textStatus) { 
          if (textStatus == "success") { 
           var thegrid = $("#Grid1")[0]; 
           thegrid.addJSONData(data.d); 
           thegrid.grid.hDiv.loading = false; 
           switch (thegrid.p.loadui) { 
            case "disable": 
             break; 
            case "enable": 
             $("#load_" + thegrid.p.id).hide(); 
             break; 
            case "block": 
             $("#lui_" + thegrid.p.id).hide(); 
             $("#load_" + thegrid.p.id).hide(); 
             break; 
           } 
          } 
         } 
        } 




        }); 


       jQuery("#Grid1").jqGrid({ 
        url: 'getdata.aspx/GetDataTable', 
        datatype: 'json', 
        mtype: 'POST', 
        colNames: ['Item Code', 'Part Number'], 
        colModel: [{ name: 'ItemCode', index: 'ItemCode', width: 200 }, 
        { name: 'PartNumber', index: 'PartNumber', width: 300}], 
        pager: '#pager', sortname: 'ItemCode', 
        viewrecoreds: true, 
        imgpath: 'JQGridReq/images', 
        serializeGridData: function (data) { 
         return $.toJSON(data); 
        } 


       }); 
      }); 






    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <table id="Grid1" class="scroll" align="center" width="100%"></table> 
    <div id="pager" class="scroll" style="text-align:center;"> 






    </div> 
    </form> 
</body> 
</html> 
+0

問題,如'Please幫幫我吧!「不需額外的幫助這裏堆棧溢出。閱讀FAQ並使用標點符號。 – Mixxiphoid

+0

當然謝謝你。 – CodeNewbie

回答

0

我發現了我自己的答案這裏是我在ASP.net和MySQL數據庫上實現JQGrid的做法。

在你的優勢ItemCode.ashx

public struct JQGridResults 
    { 
     public int page; 
     public int total; 
     public int records; 
     public JQGridRow[] rows; 
    } 



public struct JQGridRow 
    { 

     public string ItemCode; 
     public string PartNumber; 
     public string ItemDescriptionShort; 
     public string ItemDescriptionLong; 
     public string ProductCode; 
     public string GroupCode; 
     public string BusinessUnit; 
     public string[] cell; 
    } 
    [Serializable] 

public class User 
    { 
     public string ItemCode { get; set; } 
     public string PartNumber { get; set; } 
     public string ItemDescriptionShort { get; set; } 
     public string ItemDescriptionLong { get; set; } 
     public string ProductCode { get; set; } 
     public string GroupCode { get; set; } 
     public string BusinessUnit { get; set; } 
    } 

    public class ItemCode : IHttpHandler 
    { 

     public void ProcessRequest(HttpContext context) 
     { 
      HttpRequest request = context.Request; 
      HttpResponse response = context.Response; 

      string _search = request["_search"]; 
      string numberOfRows = request["rows"]; 
      string pageIndex = request["page"]; 
      string sortColumnName = request["sidx"]; 
      string sortOrderBy = request["sord"]; 


      int totalRecords; 
      Collection <User> users = GetUsers(numberOfRows, pageIndex, sortColumnName,sortOrderBy, out totalRecords); 
      string output = BuildJQGridResults(users, Convert.ToInt32(numberOfRows),Convert.ToInt32(pageIndex), Convert.ToInt32(totalRecords)); 
      response.Write(output); 
     } 
     private string BuildJQGridResults(Collection <User> users, int numberOfRows, int pageIndex, int totalRecords) 
     { 

      JQGridResults result = new JQGridResults(); 
      List<JQGridRow> rows = new List<JQGridRow>(); 
      foreach (User user in users) 
      { 
       JQGridRow row = new JQGridRow(); 
       row.ItemCode = user.ItemCode; 
       row.PartNumber = user.PartNumber; 
       row.ItemDescriptionShort = user.ItemDescriptionShort; 
       row.ItemDescriptionLong = user.ItemDescriptionLong; 
       row.ProductCode = user.ProductCode; 
       row.GroupCode = user.GroupCode; 
       row.BusinessUnit = user.BusinessUnit; 

       rows.Add(row); 
      } 
      result.rows = rows.ToArray(); 
      result.page = pageIndex; 
      result.total = (totalRecords + numberOfRows - 1)/8; 
      result.records = totalRecords; 
      JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 }; 
      //return new JavaScriptSerializer().Serialize(result); 
      return serializer.Serialize(result); 
     } 


     private Collection<User> GetUsers(string numberOfRows, string pageIndex, string sortColumnName, string sortOrderBy, out int totalRecords) 
     { 
      Collection<User> users = new Collection<User>(); 
      MySqlConnection conn = Functions.GetConnection(); 
      string sql; 
      sql = "SELECT * FROM swans.tblsomain,tblligerstatus;"; 


      MySqlCommand cmd = new MySqlCommand(sql, conn); 
      MySqlDataReader data1 = cmd.ExecuteReader(); 

      string connectionString = "server=127.0.0.1;database=swans;uid=root;password=''"; 

      using (MySqlConnection connection = new MySqlConnection(connectionString)) 
      { 
       using (MySqlCommand command = new MySqlCommand()) 
       { 
        command.Connection = connection; 
        command.CommandText = "select ItemCode,PartNumber,ItemDescriptionShort,ItemDescriptionLong,ProductCode,GroupCode,BusinessUnit from tblitemcodefromqne;"; 
        command.CommandType = CommandType.Text; 

        MySqlParameter paramPageIndex = new MySqlParameter("@PageIndex",MySqlDbType.Int32); 
        paramPageIndex.Value = Convert.ToInt32(pageIndex); 
        command.Parameters.Add(paramPageIndex); 

        MySqlParameter paramColumnName = new MySqlParameter("@SortColumnName", MySqlDbType.VarChar, 50); 
        paramColumnName.Value = sortColumnName; 
        command.Parameters.Add(paramColumnName); 

        MySqlParameter paramSortorderBy = new MySqlParameter("@SortOrderBy", MySqlDbType.VarChar, 4); 
        paramSortorderBy.Value = sortOrderBy; 
        command.Parameters.Add(paramSortorderBy); 

        MySqlParameter paramNumberOfRows = new MySqlParameter("@NumberOfRows", MySqlDbType.Int32); 
        paramNumberOfRows.Value = Convert.ToInt32(numberOfRows); 
        command.Parameters.Add(paramNumberOfRows); 

        MySqlParameter paramTotalRecords = new MySqlParameter("@TotalRecords",MySqlDbType.Int32); 
        totalRecords = 0; 
        paramTotalRecords.Value = totalRecords; 
        paramTotalRecords.Direction = ParameterDirection.Output; 
        command.Parameters.Add(paramTotalRecords); 


        connection.Open(); 

        using (MySqlDataReader dataReader = command.ExecuteReader()) 
        { 
         User user; 
         while (dataReader.Read()) 
         { 
          user = new User(); 
          user.ItemCode = Convert.ToString(dataReader["ItemCode"]); 
          user.PartNumber = Convert.ToString(dataReader["PartNumber"]); 
          user.ItemDescriptionShort = Convert.ToString(dataReader["ItemDescriptionShort"]); 
          user.ItemDescriptionLong =Convert.ToString(dataReader["ItemDescriptionLong"]); 
          user.ProductCode = Convert.ToString(dataReader["ProductCode"]); 
          user.GroupCode = Convert.ToString(dataReader["GroupCode"]); 
          user.BusinessUnit = Convert.ToString(dataReader["BusinessUnit"]); 
          users.Add(user); 
         } 
        } 
        totalRecords = users.Count; 

       } 

       return users; 
      } 

     } 



     public bool IsReusable 
     { 
      get 
      { 
       return false; 
      } 
     } 

    } 

ItemCode.aspx

<script type="text/javascript" > 
     $(function() { 
      $("#UsersGrid").jqGrid({ 
       type: 'POST', 
       url: 'ItemCode.ashx', 
       datatype: "json", 
       width: 1245, 
       height: 450, 
       serializeGridData: function (postData) { 
        return JSON.stringify(postData); 
       }, 
       jsonReader: { 
        repeatitems: false, 
        root: "rows", 
        page: "page", 
        total: "total", 
        records: "records" 
       }, 

       colNames: ['Item Code', 'Part Number', 'Short Description', 'Long Description', 'Product Code', 'Group Code', 'Business Unit'], 
       colModel: [ 
        { name: 'ItemCode', index: 'ItemCode', width: 60, editable:true, sorttype: 'string' }, 
        { name: 'PartNumber', index:'PartNumber', width: 50 }, 
        { name: 'ItemDescriptionShort',index:'ItemDescriptionShort', width: 260 }, 
        { name: 'ItemDescriptionLong',index:'ItemDescriptionLong', width: 260 }, 
        { name: 'ProductCode',index:'ProductCode', width: 50 }, 
        { name: 'GroupCode',index:'GroupCode', width: 50 }, 
        { name: 'BusinessUnit',index:'BusinessUnit', width: 50 }, 



       ], 



       cmTemplate: { title: false }, 
       rowNum: 20, 
       mtype: 'GET', 
       loadonce: true, 
       rowList: [10, 20, 30], 
       pager: '#UsersGridPager', 
       sortname: 'ItemCode', 
       multiSort: true, 
       gridview: true, 
       viewrecords: true, 

       sortorder: 'asc', 
       caption: "Item Code Summary" 


      }); 

      jQuery("#UsersGrid").jqGrid('navGrid', '#UsersGridPager', 
      { del: false, add: false, edit: false, search: false }); 
      jQuery("#UsersGrid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false }); 



     }); 

</script> 
</head> 
<body> 
<form id="UsersForm" runat="server"> 
<table id="UsersGrid" ></table> 
<div id="UsersGridPager"></div> 
</form> 
</body> 
0

數據庫表應與在這是在JavaScript中的colmodel名稱的字段名。

的Java腳本

<script language="javascript" type="text/javascript"> 

     $(function() { 
     var grid = jQuery("#myGrid"); 
     grid.jqGrid({ 
     url: "http://localhost:50530/jqGridHandler.ashx", 
     mtype:'GET', 
     datatype: "json", 
     height: 200, 
     hidegrid: false,//hides the arrow button at the top right corner for collapsing the jqGrid 
     rowNum: 10, 
     rowList: [10, 20, 30], 
     viewrecords: true, 
     caption: "Employees", 
     pager: "#pager", 
     colNames: ['FirstName', 'SecondName', 'DOB', 'EmailID','UserName'], 
     colModel: [ 
      { name: 'FirstName', index: 'FirstName', width: 100, align: "center" }, 
      { name: 'LastName', index: 'LastName', width: 100, align: "left" }, 
      { name: 'DOB', index: 'DOB', width: 100, align: "center", formatter: 'date', formatoptions: { newformat: 'm-d-Y' }, datefmt: 'm-d-Y' }, 
      { name: 'Email', index: 'EmailID', width: 120, align: "right"}, 
      { name: 'Username', index: 'Username', width: 100 } 
        ] 
    }); 
}); 

</script> 

Web組件

<table id="myGrid"> </table> 

後面的代碼(jqGridHandler.ashx)

public class jqGridHandler : IHttpHandler 
    { 

    public void ProcessRequest(HttpContext context) 
    { 
     MyFirstService.Service1Client client = new MyFirstService.Service1Client(); 
     context.Response.Write(client.GetJsonUsers()); 
    } 

    private DataSet GetUsersFromDB() 
    { 
     AccessDataBase reader = new AccessDataBase(); 
     string selectquery = "SELECT * FROM Registration"; 
     return reader.readDB(selectquery); 
    } 

    public string GetJsonUsers() 
    { 
     return GetJson(GetUsersFromDB()); 
    } 


    private string GetJson(DataSet dt) 
    { 
     System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
     List<Dictionary<string, object>> rows = 
      new List<Dictionary<string, object>>(); 
     Dictionary<string, object> row = null; 
     foreach (DataTable dtt in dt.Tables) 
      foreach (DataRow dr in dtt.Rows) 
      { 
       row = new Dictionary<string, object>(); 
       foreach (DataColumn col in dtt.Columns) 
       { 
        row.Add(col.ColumnName.Trim(), dr[col]); 
       } 
       rows.Add(row); 
      } 

     return serializer.Serialize(rows); 
    } 

    public bool IsReusable 
    { 
     get 
     { 
      return false; 
     } 
    } 
} 

AccessDB.cs

public SqlConnection Connection { get; set; } 
     public AccessDataBase() 
     { 
      Connection = new SqlConnection("Data Source=.;Initial Catalog=NewDB;Integrated Security=True"); 

     } 

     public DataSet readDB(string selectquery) 
     { 
      SqlCommand cmd = new SqlCommand(selectquery); 
      using (Connection) 
      { 
       using (SqlDataAdapter sda = new SqlDataAdapter()) 
       { 
        cmd.Connection = Connection; 
        sda.SelectCommand = cmd; 
        using (DataSet ds = new DataSet()) 
        { 
         sda.Fill(ds); 
         return ds; 
        } 
       } 
      } 
     } 

,並添加

using System.Web.Script.Serialization; 

和唐忘記添加js和css文件在母版頁。

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" /> 
    <link href="Scripts/JQGrid/jquery-ui-1.9.2.custom.css" rel="stylesheet" type="text/css" /> 
    <link href="Scripts/JQGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" /> 
    <script src="Scripts/JQGrid/jquery-1.9.0.min.js" type="text/javascript"></script> 

    <script src="Scripts/JQGrid/jquery.jqGrid.js" type="text/javascript"></script> 

    <script src="Scripts/JQGrid/grid.locale-en.js" type="text/javascript"></script> 
    <script src="Scripts/JQGrid/jquery.jqGrid.min.js" type="text/javascript"></script>