HI WELCOME TO KANSIRIS

Pass Generic List (List) as Parameter to Function in C#

Leave a Comment
Generally in c#  to send generic list as a parameter in function we need to write the code like as shown below.

C# Code


public void yourfunction(List<UserDetails> user)
{
----------------------
---- your code -----
---------------------
}


If you want complete example of sending list as a parameter in function open web application page and write code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Send Generic List as a Parameter to Function in C#, Vb.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server">

</asp:GridView>
</div>
</form>
</body>
</html>

Now open code behind file and write the code like as shown below

C# Code


using System;
using System.Collections.Generic;

public partial class SendListAsParameter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<UserDetails> userinfo = new List<UserDetails>();
UserDetails user = new UserDetails();
user.userid = 1;
user.username = "Suresh Dasari";
user.education = "B.Tech";
user.location = "Hyderabad";
userinfo.Add(user);
user = new UserDetails();
user.userid = 2;
user.username = "Rohini Alavala";
user.education = "Msc";
user.location = "Guntur";
userinfo.Add(user);
user = new UserDetails();
user.userid = 3;
user.username = "Praveen Kumar";
user.education = "B.Tech";
user.location = "Bangalore";
userinfo.Add(user);
user = new UserDetails();
user.userid = 4;
user.username = "Madhav Sai";
user.education = "MBA";
user.location = "Nagpur";
userinfo.Add(user);
BindGridview(userinfo);
}
}
public void BindGridview(List<UserDetails> user)
{
gvDetails.DataSource = user;
gvDetails.DataBind();
}
}

public class UserDetails
{
public int userid { getset; }
public string username { getset; }
public string education { getset; }
public string location { getset; }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.