Load Database Values in Ajax Cascading DropDown - ajax

This is the first time I have used Ajax, and this is also my first C#.NET project, so I am very new. I am using .NET 4.0.
I have succesfully implemented the Ajax cascading dropdown, and upon submit, the data is stored in the database. However, this page also has an "Edit" feature, meaning if there is a value for said dropdown already populated in the database, it "should" display, and allow the user to change it. This is where I get stuck. If there is already a value for these dropdowns in the db, how can I display that?
I do have a try/catch for my other non-Ajax fields, and I have tried that on these, to no avail. I'll list that as well.
Code Behind:
public partial class Research : System.Web.UI.Page
{
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
/Create data table to populate fields with values from the selected record.
DataTable dt = new DataTable();
dt = selectDetails();
//Call Try/Catch Blocks to load fields.
tryRootCauseCategoryDD(cboRootCauseCategory, dt.Rows[0]["rootCauseCategory"].ToString());
tryRootCauseDD(cboRootCause, dt.Rows[0]["rootCause"].ToString());
}
}
protected void tryRootCauseCategoryDD(DropDownList cboRootCauseCategory, string ddSelected)
{
try
{
cboRootCauseCategory.SelectedValue = ddSelected;
}
catch
{
cboRootCauseCategory.SelectedIndex = 0;
}
}
protected void tryRootCauseDD(DropDownList cboRootCause, string ddSelected)
{
try
{
cboRootCause.SelectedValue = ddSelected;
}
catch
{
cboRootCause.SelectedIndex = 0;
}
}
protected DataTable selectDetails()
{
DataTable dt = new DataTable();
dt = dataAccess.ExecuteDataTable
(
"spRecordDetails", dataAccess.DEV, new SqlParameter[1]
{
new SqlParameter ("#vRecID", Request.QueryString["recID"].ToString())
}
);
return dt;
}
ASPX:
<asp:DropDownList ID="cboRootCauseCategory" runat="server"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="ccdRootCauseCategory" runat="server" Category="RootCauseCategory"
TargetControlID="cboRootCauseCategory" PromptText="(Please select:)" LoadingText="Loading.."
ServiceMethod="BindRootCauseCategoryDetails" ServicePath="CascadingDropDown.asmx">
</ajaxToolkit:CascadingDropDown>
<asp:DropDownList ID="cboRootCause" runat="server"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="ccdRootCause" runat="server" Category="RootCause" ParentControlID="cboRootCauseCategory"
TargetControlID="cboRootCause" PromptText="(Please select:)" LoadingText="Loading.."
ServiceMethod="BindRootCauseDetails" ServicePath="CascadingDropDown.asmx">
</ajaxToolkit:CascadingDropDown>
Web Service:
[WebService(Namespace = "http://microsoft.com/webservices/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//To allow this Web Service to be called from script, using ASP.NET AJAX.
[System.Web.Script.Services.ScriptService()]
public class CascadingDropDown : System.Web.Services.WebService
{
//Database connection string
//private static string strconnection = ConfigurationManager.AppSettings["DEV"].ToString();
private static string strconnection = System.Configuration.ConfigurationManager.ConnectionStrings["DEV"].ConnectionString;
//database connection
SqlConnection conCategory = new SqlConnection(strconnection);
public CascadingDropDown()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
/// WebMethod to Populate Root Cause Category Dropdown
[WebMethod]
public CascadingDropDownNameValue[] BindRootCauseCategoryDetails(string knownCategoryValues, string category)
{
conCategory.Open();
SqlCommand cmdRootCauseCategory = new SqlCommand
("Select Distinct RootCauseCategory From RootCause", conCategory);
cmdRootCauseCategory.ExecuteNonQuery();
SqlDataAdapter daRootCauseCategory = new SqlDataAdapter(cmdRootCauseCategory);
DataSet dsRootCauseCategory = new DataSet();
daRootCauseCategory.Fill(dsRootCauseCategory);
conCategory.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> RootCauseCategoryDetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsRootCauseCategory.Tables[0].Rows)
{
//string recID = dtrow["recID"].ToString();
string RootCauseCategory = dtrow["RootCauseCategory"].ToString();
string RootCauseCategoryValue = dtrow["RootCauseCategory"].ToString();
RootCauseCategoryDetails.Add(new CascadingDropDownNameValue(RootCauseCategory,RootCauseCategoryValue));
}
return RootCauseCategoryDetails.ToArray();
}
/// WebMethod to Populate Root Cause Dropdown
[WebMethod]
public CascadingDropDownNameValue[] BindRootCauseDetails(string knownCategoryValues, string category)
{
string rootCauseCategory;
//This method will return a StringDictionary containing the name/value pairs of the currently selected values
StringDictionary rootCauseCategoryDetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
rootCauseCategory = (rootCauseCategoryDetails["RootCauseCategory"]);
conCategory.Open();
SqlCommand cmdRootCause = new SqlCommand("select recID, rootCause from RootCause where rootCauseCategory= #vRootCauseCategory", conCategory);
cmdRootCause.Parameters.AddWithValue("#vRootCauseCategory", rootCauseCategory);
cmdRootCause.ExecuteNonQuery();
SqlDataAdapter daRootCause = new SqlDataAdapter(cmdRootCause);
DataSet dsRootCause = new DataSet();
daRootCause.Fill(dsRootCause);
conCategory.Close();
//create list and add items in it by looping through dataset table
List<CascadingDropDownNameValue> rootCauseDetails = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsRootCause.Tables[0].Rows)
{
string recID = dtrow["recID"].ToString();
string rootCause = dtrow["rootCause"].ToString();
rootCauseDetails.Add(new CascadingDropDownNameValue(rootCause, recID));
}
return rootCauseDetails.ToArray();
}
}

I decided to scrap the idea of a web service, and opted for an updatepanel instead. There is likely a less redundant way to do this, but it's working.
Final Solution:
Markup page:
<asp:TableCell Width="500">
<asp:UpdatePanel ID="UpdatePanel" runat="server">
<ContentTemplate>
<p><asp:DropDownList ID="cboRootCauseCategory" runat="server" AutoPostBack="True" onselectedindexchanged="cboRootCauseCategory_SelectedIndexChanged"></asp:DropDownList>
<asp:DropDownList ID="cboRootCause" runat="server" AutoPostBack="true"></asp:DropDownList></p>
</ContentTemplate>
</asp:UpdatePanel>
</asp:TableCell>
Code Behind:
if (!IsPostBack)
{
//Create data table to populate fields with values from the selected record.
DataTable dt = new DataTable();
dt = selectDetails();
//Call Try/Catch Blocks to load fields.
tryRootCauseCategoryDD(cboRootCauseCategory, dt.Rows[0]["rootCauseCategory"].ToString());
tryRootCauseDD(cboRootCause, dt.Rows[0]["rootCause"].ToString());
}
protected void tryRootCauseCategoryDD(DropDownList cboRootCauseCategory, string ddSelected)
{
try
{
//Load Root Cause Category Drop Down
DataTable RootCauseCategories = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCauseCategory From RootCauseCategory", con);
adapter.Fill(RootCauseCategories);
cboRootCauseCategory.DataSource = RootCauseCategories;
cboRootCauseCategory.DataTextField = "RootCauseCategory";
cboRootCauseCategory.DataValueField = "recID";
cboRootCauseCategory.DataBind();
}
cboRootCauseCategory.Items.Insert(0, new ListItem("(Please select:)", "0"));
cboRootCauseCategory.SelectedValue = ddSelected;
}
catch
{
//Load Root Cause Category Drop Down
DataTable RootCauseCategories = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCauseCategory From RootCauseCategory", con);
adapter.Fill(RootCauseCategories);
cboRootCauseCategory.DataSource = RootCauseCategories;
cboRootCauseCategory.DataTextField = "RootCauseCategory";
cboRootCauseCategory.DataValueField = "recID";
cboRootCauseCategory.DataBind();
}
cboRootCauseCategory.Items.Insert(0, new ListItem("(Please select:)", "0"));
cboRootCauseCategory.SelectedIndex = 0;
}
}
protected void tryRootCauseDD(DropDownList cboRootCause, string ddSelected)
{
try
{
string cboRootCauseCategoryID = Convert.ToString(cboRootCauseCategory.SelectedValue);
DataTable RootCauses = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCause, rootCauseCategory From RootCause Where rootCauseCategory = '" + cboRootCauseCategoryID + "'", con2);
adapter.Fill(RootCauses);
cboRootCause.DataSource = RootCauses;
cboRootCause.DataTextField = "RootCause";
cboRootCause.DataValueField = "recID";
cboRootCause.DataBind();
}
cboRootCause.SelectedValue = ddSelected;
}
catch
{
cboRootCause.SelectedIndex = 0;
}
}
protected void cboRootCauseCategory_SelectedIndexChanged(object sender, EventArgs e)
{
string cboRootCauseCategoryID = Convert.ToString(cboRootCauseCategory.SelectedValue);
DataTable RootCauses = new DataTable();
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["DEV"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("Select recID, rootCause, rootCauseCategory From RootCause Where rootCauseCategory = '" + cboRootCauseCategoryID + "'", con2);
adapter.Fill(RootCauses);
cboRootCause.DataSource = RootCauses;
cboRootCause.DataTextField = "RootCause";
cboRootCause.DataValueField = "recID";
cboRootCause.DataBind();
}
cboRootCause.Items.Insert(0, new ListItem("(Please select:)", "0"));

Related

How do i convert OracleDataReader to a List object that i can store in my model MVC

I have managed to connect to the OracleDb and use the OracleDataReader to retrieve the data from the DB. The problem i have is that i now want to insert the retrieved data in my model (Invoice). The problem right now is that i cant convert the retrieved data to a type that is accepted by the model. Is there a way to convert the OracleDataReader reader to a type that is accepted by the model so i can fil the model (IEnumerable) with data?
public ViewResult search_btn(object sender, EventArgs e, string docno){
OracleConnection OC = new OracleConnection("SOMECONNECTIONSTRING");
OracleCommand getBlobRecord = new OracleCommand("select * from xx where invoice_no=:invoiceId", OC);
getBlobRecord.Parameters.Add(new OracleParameter("invoiceId", docno));
OC.Open();
using (OracleDataReader reader = getBlobRecord.ExecuteReader(CommandBehavior.SequentialAccess))
{
try
{
while (reader.Read())
{
var x = reader["invoice_no"];
var y = reader["supplier_id"];
new Invoice
{
Invoice_No = (int)x,
Supplier_Id = (int)y
};
}
reader.Close();
reader.Dispose();
return View("Index");
}
finally
{
reader.Close();
OC.Close();
}
}}

Handling Null in MVC Model

I am facing DateTime null Error. My data comes from SQL server through stored procedures in MVC project. In MVC, Employee model receive the data in List and pass it to the View through the Employee Controller. Following is the code:
public List<Employee> GetEmployeesByUserName(string username)
{
SqlConnection conn = new SqlConnection(Startup.MTSConn);
List<Employee> empList = new List<Employee>();
using (conn)
{
using (SqlCommand cmd = new SqlCommand("spRetrievEmployeesByUserName", conn))
{
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("#Username", username);
DataTable dt = new DataTable();
conn.Open();
adapter.Fill(dt);
//Convert Data to List
foreach (DataRow row in dt.Rows)
{
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
**DOB = row["DOB"]==DBNull ? DBNull : Convert.ToDateTime(row["DOB"])**
Here I want to check if the field is null then return null otherwise convert it to DateTime. In employee model it is already set to null 'public DateTime? DOB { get; set; }'
});
}
}
return empList;
}
}
I advise you to use entity to get the data from the database. However, to tackle this issue try do something like this
foreach (DataRow row in dt.Rows)
{
if (row["DOB"] != null)
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
**DOB = row["DOB"].Convert.ToDateTime()**
}
else
{
employeesList.Add(new Employee
{
UserName = row["UserName"].ToString(),
KOCNo = row["KOCNo"].ToString(),
Name = row["Name"].ToString(),
Designation = row["Designation"].ToString(),
DOB = null
}

Getting error while consuming Web API in Xamarin forms cross platform

Getting below error while consuming web API in Xamarin forms "Cannot convert from Login to System.Net.Http.HttpCompletionOption"
I'm new to mobile development ,please help me in completing the above code for consuming the API's in Xamarin cross platform.
Below is the code for WEB API
public class DBLoginController : ApiController
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_test"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = null;
[HttpGet]
[ActionName("getCustomerInfo")]
public DataTable Get()
{
DataTable dt = new DataTable();
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_admin";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
adp = new SqlDataAdapter(cmd);
dt.TableName = "tbl_admin";
adp.Fill(dt);
con.Close();
}
catch
{
}
return dt;
}
[HttpPost]
public int Login([System.Web.Http.FromBody] Login lgn)
{
int ret = 0;
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from tbl_admin where username='"+lgn.username+"'username and password='"+ lgn.password + "'";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
ret = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch
{
}
return ret;
}
}
Below is the code for consuming API in xamarin form
private async void BtnLogin_Clicked(object sender, EventArgs e)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://********.com/api/DBLogin/getCustomer");
Login lgn = new Login { username = txtUsername.Text.ToString(), password = txtPassword.Text.ToString() };
var response = client.GetAsync("api/Login/Login").Result;
var a = response.Content.ReadAsStringAsync();
if (a.Result.ToString().Trim() == "0")
{
messageLabel.Text = "Invalid login credentials.";
}
else
{
await Navigation.PushModalAsync(new Page2());
}
}
}
}
please help
Thanks in advance

How to get the DropDown selected value in controller in MVC3?

Hi all i have to get the selected value from dropdown into my post method in controller ..how can i do this
here is my controller
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddNew()
{
ViewBag.Roles = new SelectList(List(), "RoleID", "RoleName");
return View();
}
//
//Geting All Roles In a GetRoles()/
//
public List<ResourceModel> List()
{
var roles = new List<ResourceModel>();
SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True");
SqlCommand Cmd = new SqlCommand("Select GroupId,EmplopyeeRole from EmployeeGroup", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(Cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new ResourceModel();
model.RoleId = Convert.ToInt16(ds.Tables[0].Rows[i]["GroupId"]);
model.RoleName = ds.Tables[0].Rows[i]["EmplopyeeRole"].ToString();
roles.Add(model);
}
conn.Close();
return roles ;
}
//
//To perform the AddNew Logic..i.e it adds a new employee to DB/
//
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNew(ResourceModel model)
{
// var modelList = new List<ProjectModel>();
using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"))
{
conn.Open();
SqlCommand insertcommande = new SqlCommand("InsertEmplyoee", conn);
insertcommande.CommandType = CommandType.StoredProcedure;
insertcommande.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = model.EmployeeName;
insertcommande.Parameters.Add("#EmployeeEmailId", SqlDbType.VarChar).Value = model.EmployeeEmailId;
insertcommande.Parameters.Add("#EmployeePassword", SqlDbType.VarChar).Value = model.EmployeePassword;
insertcommande.Parameters.Add("#GroupName", SqlDbType.VarChar).Value = model.RoleName;
insertcommande.ExecuteNonQuery();
}
return View();
}
now i want to get the selected value #GroupName Parameter in my postmethod...can any one help how to do thi
this is my html
<%:Html.DropDownList("Roles")%>
You could have your POST action take a view model, or add another parameter to it that will hold the selected value:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNew(ResourceModel model, string roles)
And don't forget to repopulate the ViewBag.Roles in your POST action the same way you did in your GET action if you intend to redisplay the same view.
You could use Request.Form["Roles"] in your controller action.. but maybe a better solution is creating a new view model for the page and you can use Html.DropDownListFor(m => m.RoleID, rolesSelectList) or whatever.. and the value will be automatically bound to your model in the udpate method:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNew(ResourceModel model)

Sharepoint 2010 Custom Webpart - Access Denied Error

we've created a custom webpart to display announcements from all lists a user has access to, removing a few. The error we are having is that the webpart works fine on the page for the administrators, but when testing with regular user accounts, they are unable to see the page at all and are given a Access Denied error which is coming from the webpart itself.
Only when a user is added as a Site Collection Administrator they can see the page and have access to the webpart. What I'd like some advice on is how to be able to apply full read permissions to a select group within the code itself.
Below is the backend code
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
private SPWebCollection thisWeb;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
thisWeb = thisSite.AllWebs;
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
foreach (SPWeb web in thisWeb)
{
//Pull the lists from the site into a list collection
siteLists = web.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "Bulletins" || list.Title.ToString() == "The Buzz - Curriculum" || list.Title.ToString() == "The Buzz - Personal" || list.Title.ToString() == "The Buzz - Support" || list.Title.ToString() == "Critical Annoucements")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = web.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
Thanks
thisWeb = thisSite.AllWebs;
This code requires Administrator previliges. Run it under Elevated Previleges:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
Based on the above comments and edited changes, here is the full working code, encase anyone was wondering:-
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
//private SPWebCollection thisWeb;//
private SPWeb thisWeb = SPContext.Current.Web;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
//thisWeb = thisSite.AllWebs.;//
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
//Sorting, Filtering & paging does not work so has been commented out for now
//this.grid.AllowSorting = true;
//Bind the three columns to the SPGridView
//HtmlEncode must be false for the links to appear as true html
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Has been commented out due to these sections not working
//grid.AllowFiltering = true;
//grid.FilterDataFields = "Title";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "Created";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "ListName";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
{
//Pull the lists from the site into a list collection
siteLists = thisWeb.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
SPBasePermissions perms = SPBasePermissions.ViewListItems;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
if (list.DoesUserHavePermissions(perms))
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "The Buzz" || list.Title.ToString() == "Test 2 list")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = thisWeb.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
SPWeb.GetSubwebsForCurrentUser() should be used. It gets SubWebs that current user has access to. Avoid using ElevatedPriveleges until you absolutely need it.

Resources