Hey! Use A Method To Get Your SPList!

Well, maybe it is just me, but you should generally use a method in order to get a reference to your SharePoint lists. For example, you are generally getting a reference as such:

[csharp]

using(SPSite mySite = new SPSite(“http://server/”))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList myList = myWeb.Lists[“MyList”];
}
}

[/csharp]

But wouldn’t it be better to use a method?

[csharp]

public static SPList GetList(SPWeb website, string listName)
{
if (website == null)
{
return null;
}
try
{
return website.Lists[listName];
}
catch
{
return null;
}
}

[/csharp]

You could then use this between your setting of your web references. I think it is a much better, much more elegant approach when getting a reference to a list, but hell, maybe it’s just me :-)

Share

Leave a Reply

Your email address will not be published. Required fields are marked *