Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, i am new to MVC2.

I am trying to bind a simple gridview. i am tring this for last 1 week.
I found a lot of code in google. but i m very much confused to implement it.

I want code to bind gridview in mvc2 not mvc3 or something else. i want it in mvc2 only.

My code as follow.
When i am running this, its giving error in view page, at foreach loop as Object reference not set to an instance of an object.

MODEL:
C#
public class Users
    {
        string ConnString = ConfigurationManager.AppSettings["ConnString"].ToString();
        DataSet ds;
       
        [Required]
        [Display(Name = "Id")]
        public int ID { get; set; }

        [Required]
        [Display(Name = "Name")]
        public string UserName { get; set; }

        [Required]
        [Display(Name = "Age")]
        public int Age { get; set; }

        [Required]
        [Display(Name = "Gender")]
        public string Gender { get; set; }


        public DataTable GetGridData()
        {
            try
            {
                ds = new DataSet();
                SqlConnection con = new SqlConnection(ConnString);
                SqlDataAdapter ada = new SqlDataAdapter("Select Id,Name,Age,Gender from Emp", ConnString);
                ada.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception err)
            {
                throw err;
            }
        }
    }


CONTROLLER:

C#
public class GridController : Controller
    {
        //
        // GET: /Grid/

        public ActionResult Index()
        {
            DataTable dtGrid = new DataTable();
            Users objGrid = new Users();
            dtGrid = objGrid.GetGridData();

            List<users> Gridd = new List<users>();

            foreach (DataRow dr in dtGrid.Rows)
            {
                Users users = new Users();
                users.ID = Convert.ToInt32(dr["ID"]);
                users.UserName = dr["Name"].ToString();
                users.Age = Convert.ToInt32(dr["Age"]);
                users.Gender = dr["Gender"].ToString();

                Gridd.Add(users);
            }
            return View("Index", Gridd);
        }
    }

AND VIEW:
XML
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MyMVCTest.Models.Users>>" %>

<!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>Index</title>
</head>
<body>
    <div>
        <table width="50%">
            <tr>
                <td width="10%" height="30px">
                    ID
                </td>
                <td width="20%">
                    User Name
                </td>
                <td width="10%">
                    Age
                </td>
                <td width="10%">
                    Gender
                </td>
            </tr>
            <%foreach (var item in Model)
              { %>
            <tr>
                <td>
                    <%=Html.DisplayFor(x=>item.ID) %>
                </td>
                <td>
                    <%=Html.DisplayFor(x => item.UserName)%>
                </td>
                <td>
                    <%=Html.DisplayFor(x => item.Age)%>
                </td>
                <td>
                    <%=Html.DisplayFor(x => item.Gender)%>
                </td>
            </tr>
            <%} %>
        </table>
    </div>
</body>
</html>
Posted
Updated 20-Sep-12 19:53pm
v4

Hi there,

*facepalm* Aren't you guys generating the views for a specific model? Install 'ReSharper' on your VS, it helps a lot to overcome these simple mistakes.

Just add @Model List<Users> to the beginning of your view file.

Hope this helps, Regards
 
Share this answer
 
v2
Comments
Bhargava Katta 21-Sep-12 2:20am    
hi.. CodeHawkz

Could u giv sample code for this pls.
CodeHawkz 21-Sep-12 2:30am    
Hi Bhargava,

Your code is correct. The only thing missing is that, your view doesn't understand what is the exact type of your Model is. By adding the line,
@Model List<Users>
to the beginning of the view file, you tell to the parser that, your model is of the type of a List of Users. Then only the parser knows how to map the properties in your view.

Hope this helps, regards
Nkumary 10-Oct-13 7:41am    
Hi CodeHawkz...
I am getting this error:
CS1963: An expression tree may not contain a dynamic operation
for my view page....please help me

View Page

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ViewMasterPage1.Master" Inherits="System.Web.Mvc.ViewPage<mvcapplication1.models.teachers>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Grid


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Grid



<table style="width:50%;">
<tr>
<td>
TeacherID
</td>
<td>
Teacher Name
</td>
<td>
Standard ID
</td>
</tr>
<%foreach (var item in Model)
{ %>
<tr>
<td>
<%=Html.DisplayFor(x => item.TeacherID)%>
</td>
<td>
<%=Html.DisplayFor(x => item.TeacherName)%>
</td>
<td>
<%=Html.DisplayFor(x => item.StandardID)%>
</td>
</tr>
<% } %>
</table>

Nkumary 10-Oct-13 7:41am    
Hi CodeHawkz...
I am getting this error:
CS1963: An expression tree may not contain a dynamic operation
for my view page....please help me

View Page

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/ViewMasterPage1.Master" Inherits="System.Web.Mvc.ViewPage<mvcapplication1.models.teachers>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Grid


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Grid



<table style="width:50%;">
<tr>
<td>
TeacherID
</td>
<td>
Teacher Name
</td>
<td>
Standard ID
</td>
</tr>
<%foreach (var item in Model)
{ %>
<tr>
<td>
<%=Html.DisplayFor(x => item.TeacherID)%>
</td>
<td>
<%=Html.DisplayFor(x => item.TeacherName)%>
</td>
<td>
<%=Html.DisplayFor(x => item.StandardID)%>
</td>
</tr>
<% } %>
</table>

public ActionResult Index()
Dim connString As String = ConfigurationManager.ConnectionStrings("CTS_DEVConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
Dim cmd As New SqlClient.SqlCommand()
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "usp_CTS_viewcandstatusrecord"
cmd.Connection = conn
Dim sadp As New SqlDataAdapter()
sadp.SelectCommand = cmd
Try
conn.Open()
cmd.Parameters.AddWithValue("@company", CompName)
cmd.Parameters.AddWithValue("@startdate", Startdate)
cmd.Parameters.AddWithValue("@enddate", Enddate)
Dim ds As New DataSet()
sadp.Fill(ds)
ViewData("rptr_cd_deatil") = ds
actionresult.Add(users);
}
return View("Index", );
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900