How to use viewstate values of one function in another function - asp.net

I have 2 functions. In one function I have 2 viewstate values to get the direction
and sort order. Now I want to use this in another function.
I tried like this:
Session["a"] = Viewstate["a"];
Session["b"] = Viewstate["b"];
But it is returning NULL values:
private string SortDirection(string column)
{
string sortDirection = WebConstants.SortDirection.Ascending.ToString();
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == WebConstants.SortDirection.Ascending.ToString()))
{
sortDirection = WebConstants.SortDirection.Descending.ToString();
}
}
}
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
What am I doing wrong?

Related

How to populate data related to an item from the location which is same for all items in Xamarin.forms

I am developing an xamarin.forms app ,I have various fields like Item Name ,Item Number and location ,here Location of all the items are same ,by entering names or number of the items the values are generated automatically because name and number are unique but since the location number is common is for all the items I am not able to populate correct data related to a particular field ,I am using sqlite database in my project can anyone please suggest me on what basis can I generate related values ?
Here is the code
public async void OnSearch_Location(object o, EventArgs args)
{
if (location.Text == string.Empty || location.Text == null)
{
await Navigation.PushAsync(new ListValuePage("Location", filePath,
pos, list));
}
else
{
for (int p = 0; p < list.Count; p++)
{
if (list.ElementAt(p).Aisle + "." + list.ElementAt(p).Bin +
"." + list.ElementAt(p).Level == location.Text)
{
line.Text =
Convert.ToString(list.ElementAt(p).Line_Number);
location.Text = list.ElementAt(p).Aisle + "." +
list.ElementAt(p).Bin + "." + list.ElementAt(p).Level;
item.Text = list.ElementAt(p).Item_Number;
name.Text = list.ElementAt(p).Name;
if (list.ElementAt(p).Order_Qty == 0)
{
order_uom.Text = "";
}
else
{
order_qty.Text =
Convert.ToString(list.ElementAt(p).Order_Qty);
}
order_uom.Text = list.ElementAt(p).Order_UOM;
if (list.ElementAt(p).Consumption_UOM == string.Empty ||
list.ElementAt(p).Consumption_UOM == null)
{
consume_lbl.IsVisible = false;
consume_qty.IsVisible = false;
consume_uom.IsVisible = false;
}
else
{
consume_lbl.IsVisible = true;
consume_qty.IsVisible = true;
consume_uom.IsVisible = true;
if (list.ElementAt(p).Consumption_Qty == 0)
{
consume_qty.Text = "";
}
else
{
consume_qty.Text =
Convert.ToString(list.ElementAt(p).Consumption_Qty);
}
consume_uom.Text = list.ElementAt(p).Consumption_UOM;
}
}
}
}
}

How to sort ASPxGridView column nulls last?

My dataset contains null values and - by default - null values ​​come first.
When sorting the data, how do I get null values ​​last?
Handle the OnColumnSort event for your ASPxGridView as below:
protected void myGrid_CustomColumnSort(object sender, CustomColumnSortEventArgs e)
{
if (e.Column == null)
return;
if (!e.Column.FieldName.ToString().Equals("myColumnFieldName"))
return;
if (e.Value1 == DBNull.Value || e.Value1 == null)
e.Result = 1;
else
if (e.Value2 == DBNull.Value || e.Value2 == null)
e.Result = -1;
else
e.Result = Comparer.Default.Compare(e.Value1, e.Value2);
e.Handled = true;
}
And set the SortMode attribute for yout column as:
<Settings SortMode="Custom" />

queries in entity framework

i have written the following query and it is giving error Unable to cast object of type
System.Data.Objects.ObjectQuery'[ITClassifieds.Models.Viewsearch]' to type 'ITClassifieds.Models.Viewsearch'.
my code is as follows
if (zipcode.Contains(","))//opening of zipcode conatins comma
{
do
{
zipcode = zipcode.Replace(" ", " ");
zipcode = zipcode.Replace(", ", ",");
} while (zipcodecity.Contains(" "));
char[] separator = new char[] { ',' };
string[] temparray = zipcode.Split(separator);
var zipcd = (from u in db.ZipCodes1
where u.CityName == temparray[0] && u.StateAbbr == temparray[1] && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 0)
{
zipcode = vs.Zipcode;
locations = "";
}
else
{
tempStr = "";
zipcode = "";
}
}
You need to do
If it will always exist:
Viewsearch vs = zipcd.First()
If not use, and then check for null before using
Viewsearch vs = zipcd.FirstOrDefault()
You could also use Single if there will always be 1 or None.
The Distinct method returns an enumerable collection (in your case, and ObjectQuery<T>, which may contain more than one element. You can't typecast that directly to an item in the collection, you need to use one of the IEnumerable methods to get it:
Viewsearch vs = zipcd.SingleOrDefault();
if ( vs != null )
{
zipcode = vs.Zipcode;
locations = String.Empty;
}
else
{
zipcode = String.Empty;
tempStr = String.Empty;
}
SingleOrDefault will throw an exception if there is more than one item in the collection; if that's a problem, you can also use FirstOrDefault to grab the first item, as one example.
Also, unrelated to your question, but you don't need the temporary array variable for your string separators. The parameter to the Split method is a params array so you can just call it like this:
string[] temparray = zipcode.Split(',');
Replace the zipcd query with:
var cityName = temparray[0];
var stateAbbr = temparray[1];
Viewsearch vs = new Viewsearch {
Zipcode = db.ZipCodes1.Where(u.CityName == cityName && u.StateAbbr == stateAbbr && u.CityType == "D").First().ZIPCode
};

input string was not in correct format asp.net

I have a strange error. I have a page which loads values according to the country value stored in the session. it works fine for all other countries. only for particular country it is returning this error.
protected void populateDDMonth()
{
int numberOfMonths;
string monthName;
string completeCalendarFile = Path.Combine(Request.PhysicalApplicationPath + "admin\\text-files\\", calendarFile);
TextReader tr = new StreamReader(completeCalendarFile);
date_classa = tr.ReadLine(); //Get classa end date string
date_classb = tr.ReadLine(); //Get classb end date string
DateTime dateConvert_classa = DateTime.Parse(date_classa);
DateTime dateConvert_classb = DateTime.Parse(date_classb);
tr.Close();
DataTable MonthTable = new DataTable();
MonthTable.Columns.Add("Month", typeof(string));
MonthTable.Columns.Add("Date", typeof(string));
DateTime endMonth = DateTime.Today;
DDMonth.Items.Clear(); //Clear dropdown in order to re-populate
string classValue = DDClassType.SelectedValue.ToString();
if (classValue == "10" || classValue == "12" || classValue == "15")
{
endMonth = dateConvert_classa;
}
else if (classValue == "9" || classValue == "13" || classValue == "16")
{
endMonth = dateConvert_classb;
}
if (endMonth.Year > DateTime.Today.Year)
{
numberOfMonths = (endMonth.Month + 12) - DateTime.Today.Month;
}
else
{
numberOfMonths = endMonth.Month - DateTime.Today.Month;
}
for (int i = 0; i < numberOfMonths + 1; i++)
{
monthName = DateTime.Now.AddMonths(i).ToString("MMM"); //Display month as 3 letter string
DataRow MonthRow = MonthTable.NewRow();
MonthRow[0] = monthName.ToString() + " " + DateTime.Now.AddMonths(i).Year.ToString();
MonthRow[1] = DateTime.Now.AddMonths(i).ToString();
DDMonth.Items.Add(new ListItem(monthName.ToString() + " " + DateTime.Now.AddMonths(i).Year.ToString(),
DateTime.Now.AddMonths(i).ToString()));
}
if (Session["selectedMonth"] != null)
{
DDMonth.SelectedValue = Session["selectedMonth"].ToString();
}
if (!Page.IsPostBack)
{
DateTime startingDate = DateTime.Parse(DDMonth.SelectedValue.ToString());
LbCalendarCurrentMonth.Text = startingDate.ToString("MMMM");
}
}
This is a common problem with int casts and conversions within the International cultures:
http://support.microsoft.com/kb/942460
Whatever value is selected (if any) in DDMonth drop down, is not a valid date.
So the following code should work without error:
DateTime startingDate;
if (DateTime.TryParse(DDMonth.SelectedValue.ToString(), out startingDate)
{
LbCalendarCurrentMonth.Text = startingDate.ToString("MMMM");
}

Null reference exception

I have a function like this
public bool CheckMentorAccess()
{
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
if (intNoOfMembers > 0)
{
blnAllow = true;
}
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}
And then I use if like this
if ((Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
but it is throwing a null reference exception on the first line of the sample above
Can anyone help me out..
You can try
if (Session["ROLE_ID"] != null && (Int32.Parse(Session["ROLE_ID"].ToString()) == 3) && (CheckMentorAccess() == true))
{
cmbempList.Visible = true;
}
First check that Session["ROLE_ID"] exists before you use ToString.
It is always safer to use Convert.ToString.
Well, if the stack trace only points at that line, I'd guess this is the problem:
Int32.Parse(Session["ROLE_ID"].ToString())
That will throw a NullReferenceException if Session["ROLE_ID"] returns null.
(It will throw FormatException if the value exists in the session but isn't a valid integer.)
It's possible that it's the call to CheckMentor() which is failing, of course - but then your stack trace should say so. That could fail if cSQLHelper is null, for example.
Try this - check the values you are using when you call the method:
if (Session["ROLE_ID"] != null)
{
if ((Int32.Parse(Session["ROLE_ID"]) == 3) && (CheckMentorAccess()))
{
cmbempList.Visible = true;
}
}
and check in the method
public bool CheckMentorAccess()
{
if (Session["UserID"] == null)
{
throw new NullReferenceException("UserID is null");
}
bool blnAllow = false;
try
{
string strSelectMentorQuery = "SELECT COUNT(DISTINCT MLL.LED_ID) FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL " + "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString() + "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND" + " MLL.END_DATE > Getdate()";
int intNoOfMembers = Convert.ToInt32(cSQLHelper.myExecuteScalar(strSelectMentorQuery));
blnAllow = intNoOfMembers > 0;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
blnAllow = false;
}
// Return the value
return blnAllow;
}

Resources