如何使用数组将数据绑定到网格列

时间:2015-03-11 10:48:04

标签: c# sql asp.net arrays

aspx页面

<%@ Page Title="" Language="C#" MasterPageFile="~/HomeMaster.master" AutoEventWireup="true" CodeFile="V_MaterCode.aspx.cs" Inherits="V_MaterCode" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "V_MaterCode.aspx/BindDatatable",
                data: "{}",
                dataType: "json",
                success: function (data) {
                    for (var i = 0; i < data.d.length; i++) {
                        $("#grd_mastercodes").append("<tr><td>" + data.d[i].Vendor + "</td><td>" + data.d[i].SearchTerm + "</td><td>" + data.d[i].Vendor_Name + "</td><td>" + data.d[i].Street + "</td><td>" + data.d[i].City + "</td><td>" + data.d[i].Country + "</td><td>" + data.d[i].PO_Box + "</td><td>" + data.d[i].Currency + "</td><td>" + data.d[i].Sales_Person + "</td><td>" + data.d[i].Telephone_Number + "</td><td>" + data.d[i].Ext_01 + "</td><td>" + data.d[i].Ext_02 + "</td><td>" + data.d[i].Minimum_Value + "</td><td>" + data.d[i].Post_Code + "</td><td>" + data.d[i].Group + "</td></tr>");
                    }
                },
                error: function (result) {
                    alert("Error");
                }
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" LoadScriptsBeforeUI="false"
        EnablePartialRendering="false">
    </asp:ScriptManager>

     <div class="contentarea">
        <br />
        <asp:Label ID="lblsub" Style="overflow-x: auto; margin-left: 20px;" runat="server" Text="Station master data entry" />
    </div>

    <div style="margin: 0 auto; overflow: auto; padding: 10px 20px;">
        <asp:GridView ID="grd_mastercodes" runat="server" HeaderStyle-BackColor="#f79646" HeaderStyle-ForeColor="White"
            HeaderStyle-Font-Bold="false" Font-Names="Calibri"
            Font-Size="Medium" RowStyle-BackColor="White" HeaderStyle-BorderColor="Black"
            AutoGenerateColumns="False" RowStyle-BorderColor="Black" OnRowCreated="grd_mastercodes_RowCreated">
        </asp:GridView>
    </div>
</asp:Content>

背后的代码

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.Drawing;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using AjaxControlToolkit;

public partial class V_MaterCode : System.Web.UI.Page
{
    string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

    bool rowset = false;
    GridView dgv = new GridView();
    // For First gridview
    String[] gridColumnNames_mastercodes = { "Vendor Code", "Search Term", "Vendor Name", "Street", "City", "Country", "Post Box", "Currency", "Sales Person", "Telephone Number", "Ext_01", "Ext_02", "Minimum Value", "Post Code", "Group" };
    String[] gridColumnwidth_mastercodes = { "50px", "200px", "200px", "150px", "100px", "100px", "100px", "100px", "150px", "150px", "150px", "150px", "100px", "100px", "100px" };
    int[] gridColumnWidth_mastercodes = { 3, 15, 15, 13, 10, 10, 10, 10, 13, 13, 13, 13, 10, 10, 10 };
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
        if (!IsPostBack)
        {
             //For First gridview
                    DataTable dt = new DataTable();
                    for (int c = 0; c < gridColumnNames_mastercodes.Length; c++)
                    {
                        DataColumn dcol = new DataColumn(c.ToString(), typeof(System.Int32));
                        dcol.ColumnName = gridColumnNames_mastercodes[c];
                        dt.Columns.Add(dcol);

                        TemplateField tf = new TemplateField();
                        tf.HeaderStyle.Font.Bold = false;
                        tf.HeaderText = gridColumnNames_mastercodes[c];
                        tf.HeaderStyle.Width = new Unit(gridColumnwidth_mastercodes[c]);
                        grd_mastercodes.Columns.Add(tf);
                    }
                    for (int i = 0; i < 15; i++)
                    {
                        dt.Rows.Add(dt.NewRow());
                    }
                    grd_mastercodes.DataSource = dt;
                    grd_mastercodes.DataBind();
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message.ToString();
                System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
            }
        BindColumnToGridview();
    }

    private void BindColumnToGridview()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Vendor");
        dt.Columns.Add("Search Term");
        dt.Columns.Add("Vendor Name");
        dt.Columns.Add("Street");
        dt.Columns.Add("City");
        dt.Columns.Add("Country");
        dt.Columns.Add("Post Box");
        dt.Columns.Add("Currency");
        dt.Columns.Add("Sales Person");
        dt.Columns.Add("Telephone Number");
        dt.Columns.Add("Ext_01");
        dt.Columns.Add("Ext_02");
        dt.Columns.Add("Minimum Value");
        dt.Columns.Add("Post Code");
        dt.Columns.Add("Group");
        dt.Rows.Add();
        grd_mastercodes.DataSource = dt;
        grd_mastercodes.DataBind();
        //grd_mastercodes.Rows[0].Visible = false;
    }
    [WebMethod]
    public static UserDetails[] BindDatatable()
    {
        string connectionstring = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

        DataTable dt = new DataTable();
        List<UserDetails> details = new List<UserDetails>();

        using (SqlConnection con = new SqlConnection(connectionstring))
        {
            using (SqlCommand cmd = new SqlCommand("Select * From ArR_VendorMaster", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    UserDetails user = new UserDetails();
                    user.Vendor = dtrow["Vendor"].ToString();
                    user.SearchTerm = dtrow["SearchTerm"].ToString();
                    user.Vendor_Name = dtrow["Vendor_Name"].ToString();
                    user.Street = dtrow["Street"].ToString();
                    user.City = dtrow["City"].ToString();
                    user.Country = dtrow["Country"].ToString();
                    user.PO_Box = dtrow["PO_Box"].ToString();
                    user.Currency = dtrow["Currency"].ToString();
                    user.Sales_Person = dtrow["Sales_Person"].ToString();
                    user.Telephone_Number = dtrow["Telephone_Number"].ToString();
                    user.Ext_01 = dtrow["Ext_01"].ToString();
                    user.Ext_02 = dtrow["Ext_02"].ToString();
                    user.Minimum_Value = dtrow["Minimum_Value"].ToString();
                    user.Post_Code = dtrow["Post_Code"].ToString();
                    user.Group = dtrow["Group"].ToString();
                    details.Add(user);
                }
            }
        }
        return details.ToArray();
    }

    public class UserDetails
    {
        public string Vendor { get; set; }
        public string SearchTerm { get; set; }
        public string Vendor_Name { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string PO_Box { get; set; }
        public string Currency { get; set; }
        public string Sales_Person { get; set; }
        public string Telephone_Number { get; set; }
        public string Ext_01 { get; set; }
        public string Ext_02 { get; set; }
        public string Minimum_Value { get; set; }
        public string Post_Code { get; set; }
        public string Group { get; set; }
    }

    //For First Gridview
    protected void grd_mastercodes_RowCreated(object sender, GridViewRowEventArgs e)
    {
        try
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int rc = 0; rc < grd_mastercodes.Columns.Count; rc++)
                {
                    TextBox txtBox = new TextBox();
                    txtBox.ID = "Excel_mastercodes" + e.Row.RowIndex + "_" + rc;
                    txtBox.MaxLength = gridColumnWidth_mastercodes[rc];
                    txtBox.Width = new Unit(gridColumnwidth_mastercodes[rc]);
                    txtBox.BorderStyle = BorderStyle.None;
                    e.Row.Cells[rc].Controls.Add(txtBox);
                    e.Row.Cells[rc].Attributes.Add("onKeyDown", "enter(this);");
                    if (rc == 3)
                        txtBox.Style["text-align"] = "left";
                    else
                        txtBox.Style["text-align"] = "center";
                }
            }
        }
        catch (Exception ex)
        {
            string msg = ex.Message.ToString();
            System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('" + msg + "');", true);
        }
    }
}

enter image description here

我需要绑定数据,但它只显示列名。它没有绑定任何数据。天气我正在做的正确。如果有人知道如何获取数据,请建议我。我正在使用数组,我不知道如何绑定数组中的数据。我需要你的帮助

0 个答案:

没有答案