storing multiple values in single viewstate object - c#

hi guy's here is one problem regarding asp.net state managenment.
I want to store three values into single viewstate.Is it possible to store in single or i will go for three viewstate variables.
the basic need is that,I am using gridview rowcommand event for finding three values.
and i wanted to use these values in button_click event.it is directely not possible so i prefer viewstate.
if any other way to do this you can post.I am new in .net development so please share some knowledge of you.

You can make a class, and mark it with a Serializable attribute. Then make a list instance of that class and store it as 1 item in the viewstate. This is when you have a lot of values to store. However yours is a simple case I think:
[Serializable()]
class SomeData
{
public string Value1 {get; set;}
public string Value2 {get; set;}
public string Value3 {get; set;}
}
Add to viewstate:
ViewState.Add("myData", new SomeData () {Value1 = "A",
Value2 = "B",
Value2 = "3"});
Retrieve back from ViewState on postback:
var data = (SomeData)ViewState["myData"];
Label1.Text = string.Format("{0}, {1}, {2}",
data.Value1, data.Value2, data.Value3);

You can use whatever separator you want.
But your code would be a lot cleaner if you used three separate variables.
Let .net handle the viewstate. Using one variable seems like an unnecessary complication.

In your scenario you don't need ViewState - you can store them in variables in the code behind because the rowcommand and button_click will both fire on the same post back. You only need to store items in ViewState if they're needed across post backs.

You can use any separator. For e.g.:
ViewState["items"] = item1 + "~" + item2 + "~" + item3
For retrieving values from ViewState, split the values by "~".

Related

C# MVC Saving multiple search strings for pagination

I've seen examples on here for saving one string to pass onto the next page. But, I haven't been able to find or figure out how to save multiple search parameters without requiring a variable for each search string, which is something I'd rather not do, as I have 12 search fields.
I've seen examples with saving your variables to a viewbag and then passing that when you go to the next page. That works for the one variable, but not for multiple.
Is there a more eloquent solution then to have to pass individual view bags for each variable?
Thanks!
You can use a class for it like this:
public class SearchField
{
public string Field1 { get; set; }
public int Field2 { get; set; }
// other fields
}
And save object to ViewBag like this:
SearchField objSearchField = new SearchField();
objSearchField.Field1="value1";
objSearchField.Field2 = 100;
// set other fields
ViewBag.SearchFields = objSearchField;
You can use viewbag or tempdata["stringid"]. tempdata might be a better choice here. What you will do is create an array of strings (or a list might be even better!) and store all your information in that array. Then you store it on tempdata. Something like this:
string[] URLs = new string[12];
//do stuff
Tempdata["URLs"] = URLs;
When you get to the page you need the URLs in again, either in the controller or in the view you will write:
string[] URLS = (string[])Tempdata["URLs"];
//do stuff
or
string[] URLS = Tempdata["URLs"] as string[];
Something like that should work. You should read up on the other ways to pass data in ASP MVC:
http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/various-ways-to-pass-data-from-controller-to-view-in-mvc/
Passing an object array as TempData[] to view

Passing multiple variables between pages and using them

I have three variables I'm trying to pass from one page to another: Two checboxlists (just the checked values) and one DateTime.
I'm getting the checked items like this (this is just for one of these checkboxlists which is called lstUsers):
string cblvalues = "";
foreach (ListItem cbitem in lstUsers.Items)
{
if (cbitem.Selected)
{
cblvalues += cbitem.Value + "-";
}
}
cblvalues = cblvalues.Trim('-');
Response.Redirect("Results.aspx?cblvalues=" + cblvalues);
How would I pass the other checkboxlist and the DateTime to "Results.aspx" as well? I've seen a few different examples such as Server.Transfer, and I'm not sure which one is correct here.
And for using them on the Results.aspx page, would I just do:
string cblvalues = Request.QueryString["cblvalues"];
You can put as many values as you like on the query string. (Though as query strings get very long the web server would eventually impose a limit.) Here you simply append one key/value pair:
Response.Redirect("Results.aspx?cblvalues=" + cblvalues);
Just use a & to separate additional key/value pairs:
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&moreValue=" + moreValues);
If you do get to the point where the query string becomes absurdly long and you basically have a lot of data to pass to the next page, then you'd be looking at other ways of doing this. A simple alternative may be to store the values in session state, redirect the user, then pull the values from session state. Something as simple as this:
Session["cblvalues"] = cblvalues;
Session["moreValues"] = moreValues;
Response.Redirect("Results.aspx");
Then in Results.aspx you can get the values:
var cblValues = Session["cblvalues"];
// etc.
You might also clear the session values once you get them, if the session doesn't need to keep carrying them:
Session.Remove("cblvalues");
You can pass multiple values through query string by seperated them with a &
so your snippet will be like the following:
Let cblSecond be the second combobox then;
// Building first value here
foreach (ListItem cbitem in cblSecond.Items)
{
if (cbitem.Selected)
{
cblSecondValues += cbitem.Value + "-";
}
}
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&cblSecondValues=" + cblSecondValues);
So that you can access them separately like this:
string cblvalues = Request.QueryString["cblvalues"];// gives you the first value
string cblSecondValues= Request.QueryString["cblSecondValues"];// gives you the second value
Response.Redirect(String.Format("Results.aspx?value1={0}&value2={1}&value3={2}", Value1, Value2, Value3));
If you really want to pass them using querystring then you ahouls include them as well
Response.Redirect("Results.aspx?cblvalues=" + cblvalues + "&cblvalues1=" + cblvalues + "&datetimemy=" + datetimevalue);
Form of a query string like below
http://server_name/path/aspxfile?field1=value1&field2=value2&field3=value3..&fieldn=valuen
As other answer mentioned, there are multiple ways like using Session or cookies or as well you can expose those control values as public properties and use then in next page using Page.PreviousPage property but the restriction is that you will have to use either of Server.Transfer() or Server.Execute() method instead of Response.Redirect.

Display class object in GridView

I have such a situaton, that I am reading txt file making some operation on the lines and at the end I want to display everything in gridview. I have 3 separated columns. In first and second one I am displaying normal string values. But in middle one I have object returned by one class and I would like to display it normally in my gridview. How can I achieve it? I have something like this so far.
while ((line = sr.ReadLine()) != null)
{
string[] lines = line.Split(",".ToCharArray());
object returnValue;
MyColumns object = new MyColumns();
object.Time = line[0];
object.System_Description = line[1];
object.User_Description = line[2];
///earlier in my code I have object of class called method
returnValue = method.MyMethod(mc.System_Description);
Class main = new Class();
main.Data1= object.Time;
main.ProblemData= returnValue;
main.Data2= object.User_Description;
list3.Add(main);
}
this.dataGridView3.DataSource = list3;
I have problem with showing ProblemData. Now in this column gridview shows me "project_name.Class_Name" (name of the class that this value was retured by)
EDIT:
Ok, I also have to mention that this class, from which returnValue gets values has 5 properties, let's say Categry, Name, Second_Name, Status and Value. This returnValue holds all this 5 properties with their current values.
EDIT2: Maybe someone knows how to display all this fields in one column? How can I join them only for displaying purpose? When I make normal List and insert this returnValue, it creates these 5 columns and insert values inside. Maybe it will make it easier to understand.
Please see my first comment on your question.
You have to use a nested GridView inside your second column which will bind to the returnValue. This is because GridView cannot automatically cascade your object datasource. The inner binding needs to be done in the RowDataBound event of your main GridView. For this to work, you will have to re-organise / re-factor your code.
Alternatively, you can concatenate the properties of the returnValue if their string representations can work for your scenario.
Edit:
The OP is asking about WinForms DataGridView (not ASP.Net):
The WinForms DataGridView does not support nesting out-of-the-box. However, there are some templating workarounds which are complicated. You are looking for a simple solution. I found one which can serve your immediate needs.
Hook into the CellFormatting event.
if (e.value is YOUR_OBJECT_TYPE) {
e.Value = (e.Value as YOUR_OBJECT_TYPE).YOUR_PROPERTY_NAME;
}
For details please refer to this: Binding to Nested Properties
Alternate option:
The alternate option of concatenating the properties of the returnValue as string, will also work.
main.ProblemData = "Cat: " + returnValue.Category + ", Name: " + returnValue.Name;
you should have defined your class variables like a propertiesbecause you are using them in databinding. like this..
public String Data1 {get;set;}
also make your list a ObservableCollection as it will notify the view whenever you change something in your list..
Two options
Override ToString() method in your ProblemData type
public class ProblemData
{
//whatever...
public override string ToString()
{
return string.format("{0}", this.SomeObject); //set proper display
}
}
public class YourClass()
{
//...
public ProblemData ProblemData{ get; set;}
}
Or you can set grid column formatter if object type can be formatted using string.Format
dataGridView3.Columns["ProblemData"].DefaultCellStyle.Format = "N";
//display string.Format({0:N}

Remove a property/column from a generic list

Due to some reason I cannot change the query so I have to do this in C#.
I have a class:
public class myClass
{
int id { get; set; }
string name { get; set; }
DateTime sDate { get; set; }
bool status { get; set; }
}
The data I am getting is fetched in this list. Now what I want is to remove those properties from a list that has null values. I may sound insane but you read it right. I thought of creating another list with only the selected properties, but any of the above properties can be null. So I have to devise a mechanism to filter my list based on this.
For more clarity consider the following example.
List<myClass> lstClass = some data source.
After getting the data the generic list(lstClass) looks like this.Consider the result set in a table:
Id Name Sdate status
1 a null null
2 b null null
3 c null false
Can i some how make my list look like this after removing the property sdate.
So the new list that I want to create should have only three properties.
Id Name status
1 a null
2 b null
3 c false
Any ideas? Can I do this using Linq?
PS: This has nothing to do with presentation. I don’t have a grid where I am not able to hide columns that Is not what I am looking for.
Assuming you have a generic list of myClass instances, you can create an anonymous type with only the needed properties:
List<myClass> list = ...;
var reducedList = list.Select(e => new {e.id, e.name, e.status}).ToList();
// note: call to ToList() is optional
foreach (var item in reducedList)
{
Console.WriteLine(item.id + " " + item.name + " " + item.status);
//note: item does not have a property "sDate"
}
I'm not sure you should solve your issue in the Data, but rather it's a presentation problem.
In which control do you want to display it ? Let's say you display it in DataGrid with AutoGenerateColumns=True, then you can 1) loop on columns/properties 2) for each column/property see if all property values for all rows are null and if so set column's visibility to Collapsed.
If you generate your columns by yourself it's even simpler : only add columns when content is not null for all rows.
If your DB content is dynamic, you might want to bind each row's visibility to a property that would state wether all rows are null or not for that property. Depending on how generic you want your code to be, the code might be very different, and in case you want to have generic solution, using Reflection to retrieve/get/set properties might be of some use.

How should I store a small amount of event data and share it between two asp.net pages?

I am a PHP developer and have been asked to make some amends to an Asp.Net site. There is a hardcoded table on one page which contains event information (Date, venue etc). The page uses javascript to toggle table row colours based on whether the event has already happened.
I need to add a block on another page which displays 2 upcoming events based on the current date. What is the simplest way to store and share the event data between pages? There is no database available so it needs to be a local file or array etc.
I would appreciate some insight on any good libraries / techniques which would be appropriate. This is for a simple, low-traffic site.
Create a small class that represents your Event, then you can store it in the Session state:
public class EventInfo
{
//c# auto-implemented properties
public string Bla {get; set;}
public int Bla2 {get; set;}
}
//set on one page
var eventInfo = new EventInfo();
eventInfo.Bla = "bla";
eventInfo.Bla1 = 2;
Sesssion["eventinfo"] = eventInfoObject;
//get on another
var eventInfo = (EventInfo)Session["eventinfo"]; //add null checks etc
string bla = eventInfo.Bla;
int Bla2 = eventInfo.Bla2;
//************************************************//
//set multiple events in Session
List<EventInfo> events = new List<EventInfo>();
events.Add(new EventInfo{ Bla= "bla", Bla1 = 2});
events.Add(new EventInfo{ Bla= "bla2", Bla1 = 3});
Sesssion["eventCollection"] = events ;
//get
List<EventInfo> events = (List<EventInfo>)Session["eventCollection"]; //add null checks etc
foreach(EventInfo event in Events)
{
string bla = event.Bla;
int Bla2 = event.Bla2;
}
you can use session for it.
Session["data"] = value;
you can store any object in session and cast it while retrieving it, like
Session["data"] = 1;
and
int value = Session["data"] != null ? (int)Session["data"] : 0
something like that.
The easiest way would be to use Session variables.

Categories