Archive for the ‘C#’ Category

While working in C#, I got this error that was at first a bit difficult to decipher. I removed some of the actual variable terminology, but the overall error message is below.

Inconsistent accessibility: property type is less accessible than property

All this error message really means is that there is a public method that is illegally exposing a private property. Therefore, an easy fix (but not necessary the right one), is to change private property to public. I say this may not be the right approach because this may leave a security hole in your page and may not be how the page was originally designed.

When using a DataTable as a DataSource to a GridView in C#, it is often necessary to add additional rows, whether they be blank rows or fully populated rows, to the control. It has been my experience that it is much easier to add a DataRow into the DataTable prior to a DataBind.

The first step is to create an empty datatable. It would be perfectly legal to start with a datatable prepopulated with data. In this case, we are naming the Datatable, dt.

DataTable dt = new DataTable();

The next step is to create a new DataRow object. In this case, we are calling it “newRow”. The next step would be to initialize the DataRow object, which is the second line below:

DataRow myNewRow;
myNewRow = dt.NewRow();

Now that the DataRow has been created and initialized, simply add values to the object as you would an array. In the two examples below, we are adding values to two different columns in our row. We are first assigning the column with name customerId the integer value of 1. Secondly, we are assigning the column with name username a string johndoe. Repeat as needed.

myNewRow["customerId"] = 1;
myNewRow["username"] = “johndoe” ;

Finally, we want to add this newly created row (with two columns) to the originally blank datatable we created in the beginning.

dt.Rows.Add(myNewRow);

All the steps from above are put together in the example below:

DataTable dt = new DataTable();
DataRow myNewRow;
myNewRow = dt.NewRow();
myNewRow["customerId"] = 1;
myNewRow["username"] = “johndoe” ;
dt.Rows.Add(myNewRow);

With that you can now set this datatable as a DataSource and DataBind a GridView or any other similar C# control.

It’s common practice to store certain values in session variables to allow for easy access of data between page loads. This is known as a Server Variable in C#. Assume a server variable name of “foo“. It would be accessed as:

string myValue = Request.ServerVariables.Get(”foo“);

If you get the following error message: The name “Request” does not exist in the current context, try the following:

string myValue = System.Web.HttpContext.Current.Request.ServerVariables.Get(”foo“);