In my code, after i choose the value in the drop down list and hit enter it send the first value of the drop down list instead
May I know what are the possible causes?
Below is my code:
protected void Button1_Click(object sender, EventArgs e)
{
if (DayBox.Text != "" && MonthBox.Text != "" && YearBox.Text != "")
{
string date;
int container = Convert.ToInt32(DayBox.Text);
if (container < 10)
{
date = String.Format("0{0}/{1}/{2}", DayBox.Text, MonthBox.Text, YearBox.Text);
}
else
{
date = String.Format("{0}/{1}/{2}", DayBox.Text, MonthBox.Text, YearBox.Text);
}
Session["DATE"] = date;
Session["IPADDRESS"] = IPDropDownList.Text;
Response.Redirect("IPAddressDay.aspx");
}
}
Code for the dropdown box:
//this if statment is for gettting the ip address for that Month;
if (DayBox.Text == "" && MonthBox.Text != "" && YearBox.Text != "")
{
IPDropDownList.Items.Clear();
string date;
date = String.Format("{0}/{1}",MonthBox.Text, YearBox.Text);
sqlStatment = String.Format("SELECT IPAddress FROM IPActivity WHERE AccessDate LIKE '%{0}' GROUP BY IPAddress;", date);
MyDataSet = RetriveDataBase(connection, sqlStatment, tableName);//method written by me
dra = MyDataSet.Tables[tableName].Rows;
foreach (DataRow dr in dra)
{
IPDropDownList.Items.Add(dr[0].ToString());
}
//this is to close the if statment for gettting the ip address for that Month;
}
Description:
It will not read the value I choose, but take the first value instead and send to next page
Try this:
Session["IPADDRESS"] = IPDropDownList.SelectedValue;
then, to set the value:
IPDropDownList.SelectedValue = Session["IPADDRESS"] != null ? Session["IPADDRESS"].ToString() : "" ;
And don't reset your dropdownlist if you're posting back.
if(!IsPostBack)
{
//Code to set dropdownlist values here
}
Assuming you fill your DropDownList at your Page_Load event, you need to use IsPostBack. Everytime you hit the button Page_Load event is fired before your Button1_Click event. Therefore, at your Button1_Click you get the first value in dropdownlist always. Correct code should be,
if (!IsPostBack && DayBox.Text == "" && MonthBox.Text != "" && YearBox.Text != "")
{
IPDropDownList.Items.Clear();
string date = String.Format("{0}/{1}",MonthBox.Text, YearBox.Text);
sqlStatment = String.Format("SELECT IPAddress FROM IPActivity WHERE AccessDate LIKE '%{0}' GROUP BY IPAddress;", date);
MyDataSet = RetriveDataBase(connection, sqlStatment, tableName);
foreach (DataRow dr in MyDataSet.Tables[tableName].Rows;)
{
IPDropDownList.Items.Add(dr[0].ToString());
}
}
You need:
Session["IPADDRESS"] = IPDropDownList.SelectedValue;
As select boxes have a value property which gets the value of the option which can differ from the text displayed.
Related
I have a listbox with a list of items that get loaded when you navigate to a certain page. Then I have an on click that passes parameters to an AddProducts method. That method is what loops through all selected items and inserts values from the fields filled in as well as takes the values from the listItems and adds them as parameters to a stored procedure.
The problem I'm running into is that when looping through the listItems
if(selectedItem.Selected) is returning false, but in my method where I load the listbox I initialize a SelectedValue so I'm not sure why it's giving me the error message I have for no selected items. I was able to get it to work yesterday before I moved LoadListBoxCategories outside of LoadAddData but unsure as to why that would have any effect to if(listItem.Selected).
I'm relatively new to asp.net so any help/ explanation as to why my code isn't working is extremely appreciated. I've spent the last three days trying to figure this out and haven't found a solution that works.
Code:
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session[IS_LOGGED_IN] == null)
{
Response.Redirect("/utilities/companydata/login.aspx", true);
return;
}
gvTextInputs.RowEditing += new GridViewEditEventHandler(gvTextInputs_RowEditing);
if (!IsPostBack)
{
string pageId = Request.QueryString["pageid"];
string productId = Request.QueryString["productid"];
/* Add Mode */
if (!string.IsNullOrEmpty(pageId))
{
SetMode(MODE_ADD, "");
LoadAddData(pageId);
LoadListBoxCategories(pageId);
}
else if (!string.IsNullOrEmpty(productId))
{
string imageServer;
if (LoadProductData(productId, out imageServer))
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
SetMode(MODE_EDIT, imageServer);
SetImageServer(imageServer);
}
else
{
//TO DO - Return Error
}
}
}
else
{
InitImageGridview();
InitTextGridview();
InitStaticGridview();
}
}
Load ListBox:
private void LoadListBoxCategories(string pageId)
{
listBoxCategories.Visible = true;
//This gets query is so I can store the CompanyId and the CombinedValue data from pageId
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, (CAST(wp.pageId as varchar(200)) +'|'+ CAST(wp.productTypeId as varchar(200)) + '|' ) AS CombinedValue FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource connectionId = new SqlDataSource(DB_CONNECT, select);
connectionId.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)connectionId.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
string curCategoryProductTypeId = dView.Table.Rows[0]["CombinedValue"].ToString();
// EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId
// Lists All Categories #companyId has Active
string selectLoadData = "EXEC MCAdmin_GetAllCategoriesByCompanyId #companyId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, selectLoadData);
conn.SelectParameters.Add("companyId", companyId);
lstCategoriesBox.Items.Clear();
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
// Pre-selects the value of the productTypeId you are trying to add a product for
// to send later run against a foreach insert in AddProduct()
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
testOutcomeCategory.InnerText = curCategoryProductTypeId;
lstCategoriesBox.DataSource = conn;
lstCategoriesBox.DataBind();
}
}
AddProduct:
private string AddProduct(string companyId, out string errMsg)
{
foreach (ListItem selectedItem in lstCategoriesBox.Items)
{
if (selectedItem.Selected)
{
// assign current productTypeId & pageId from selected Categories new CombinedValue column
string[] splitColumnValue = selectedItem.Value.Split('|');
string selectedPageId = splitColumnValue[0].ToString();
string selectedProductTypeId = splitColumnValue[1].ToString();
SqlDataSource connnection = new SqlDataSource(DB_CONNECT, "");
connnection.InsertCommand = "EXEC MCAdmin_AddProductFromClassic #pageId, #productTypeId, #productCode, #imgDirectory, #numSides, #sortOrder, #isActive, #template, #template2, #template3, #EditorJson, #MockupTemplateBase, #MockupTemplateTreatment, #BorderDefault ";
connnection.InsertParameters.Add("pageId", selectedPageId);
connnection.InsertParameters.Add("productTypeId", selectedProductTypeId);
connnection.InsertParameters.Add("productCode", txtProductCode.Text);
connnection.InsertParameters.Add("numSides", ddlNumSides.SelectedValue);
connnection.InsertParameters.Add("sortOrder", txtSortOrder.Text);
connnection.InsertParameters.Add("isActive", ddlActive.SelectedValue);
connnection.InsertParameters.Add("template", txtTemplate1.Text);
connnection.InsertParameters.Add("template2", txtTemplate2.Text);
connnection.InsertParameters.Add("template3", txtTemplate3.Text);
connnection.InsertParameters.Add("EditorJson", txtJson.Text);
connnection.InsertParameters.Add("MockupTemplateBase", txtMockupTemplateBase.Text);
connnection.InsertParameters.Add("MockupTemplateTreatment", txtMockupTemplateTreatment.Text);
connnection.InsertParameters.Add("BorderDefault", txtBorderDefault.Text);
/* Special Product Code for Upload Artwork Business Card */
if (txtProductCode.Text.ToUpper() == "BPFAH1-001-100")
{
connnection.InsertParameters.Add("imgDirectory", "/images/business-cards/general/");
}
else
{
connnection.InsertParameters.Add("imgDirectory", ddlImgDir.SelectedValue);
}
int result = connnection.Insert();
if (result > 0)
{
SqlDataSource connect = new SqlDataSource(DB_CONNECT, "");
connect.SelectCommand = "SELECT TOP 1 wtpProductId FROM WtpProducts ";
connect.SelectCommand = "WHERE productTypeId=#productTypeId AND pageId=#pageId DESC ";
connect.SelectParameters.Add("pageId", selectedPageId); //
connect.SelectParameters.Add("productTypeId", selectedProductTypeId); //
DataView dView = (DataView)connect.Select(DataSourceSelectArguments.Empty);
if (dView.Table.Rows.Count == 1)
{
string wtpProductId = dView.Table.Rows[0]["wtpProductId"].ToString();
errMsg = "";
return wtpProductId;
}
else
{
errMsg = "ERROR: Could not get productId of newly created Product.";
return "0";
}
}
else
{
errMsg = "ERROR: Could not add WtpProduct record to DB";
return "0";
}
}
else
{
errMsg = "ERROR: You must select a Category";
return "0";
}
}
errMsg = "ERROR: Did not make it into the foreach loop";
return "0";
}
OnClick method:
protected void OnClick_btnAddProduct(object sender, EventArgs e)
{
string pageId = Request.QueryString["pageid"];
testOutcomeCategory.InnerText = lstCategoriesBox.SelectedValue; // This proves that I have something selected!!!
string select = "SELECT companyName, cl.GbsCompanyId, cl.companyId, wpt.productTypeId, productName, baseImgDirectory, templateDirectory, wp.imageServer FROM CompanyList cl, WtpPages wp, WtpProductTypes wpt WHERE cl.companyId=wp.companyId AND wpt.productTypeId=wp.productTypeId AND wp.pageId=#pageId";
SqlDataSource conn = new SqlDataSource(DB_CONNECT, select);
conn.SelectParameters.Add("pageId", pageId);
DataView dView = (DataView)conn.Select(DataSourceSelectArguments.Empty);
if(dView.Table.Rows.Count == 1)
{
string companyId = dView.Table.Rows[0]["companyId"].ToString();
if (!string.IsNullOrEmpty(pageId))
{
string errMsg;
string productId = AddProduct(companyId, out errMsg);
if(productId != "0")
{
Response.Redirect("/utilities/companydata/add-edit-wtp-product.aspx?productid=" + productId, true);
SetStatusMsg("Success", false);
}
else
{
SetStatusMsg(errMsg, true);
}
}
}
}
The list box instance is recreated on the server-side during the postback (as well as entire page). You do not set the selected items in the Page_Load event handler - if (!IsPostBack) goes to else branch. This is why you don't see them.
Ok,
lstCategoriesBox.Items.Clear();
Ok, above goes nuclear - blows out the list, blows out the selection.
Ok, that's fine
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
Ok, above adds a new item. Should be ok, but one should setup the lb BEFORE adding any data - including that "--select--" row.
It just makes sense to "setup" the lb and THEN start adding data, right?
However, But, if above works - ok, then lets keep going, but I would setup the lb before adding any rows of data. Say like this:
lstCategoriesBox.DataTextField = "productName";
lstCategoriesBox.DataValueField = "CombinedValue";
lstCategoriesBox.Items.Add(new ListItem("--Select--", null));
Now, the next line:
lstCategoriesBox.SelectedValue = curCategoryProductTypeId;
Ouch! - we just cleared the lb, and now we trying to set it to a value? You can't do that - the lb just been cleared, right? You would need to load up the lb first, and THEN you can set it to the selected value, right?
I might be missing something here, but that lb needs to be loaded up with valid data BEFORE you attempt to set the selected value?
To test first, change following
Outcome Category.InnerText = list CategoriesBox.SelectedValue;
to
Category.InnerText = Request.Form["CategoriesBox-ClientID"]
If the data is coming in correctly, the list view cleared or reloaded when between reload and click events the page.
UPDATE: I just figured it out! So stupid but when I check if(selectedItem.Selected) since I'm looping through the ListBox items it starts at the first index of the ListBox and since the first isn't selected then that if goes to the else block. Remove the else and it works fine
dropdownlist selected value is not changing. although the string _month also contain the value but dropdownlist is not getting it.all other are working fine but only ddlMonth.selected value is not changing.i have assigned _month value to it but its not changing why? only ddlMonth is not changing all other are working fine why ddlmonth is not changing?
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue = _Month;
///here ddlMonth.selected value is not getting new value from _month
}
Other code is below
protected void Page_Load(object sender, System.EventArgs e)
{
if (Page.IsPostBack)
return;
try
{
OnLoad();
GetYears();
if (!string.IsNullOrEmpty(ddlYear.SelectedValue))
hYearId.Value = ddlYear.SelectedValue;
GetPeriods(Convert.ToInt32(hYearId.Value));
GetDepartment();
GetSection();
#region Get Selected login user department and section
ddldepartment.SelectedValue = CommonMethods.UserContext.EmployeeDeparmentID;
ddlSection.SelectedValue = CommonMethods.UserContext.EmployeeSectionID;
#endregion
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
string name = Request.QueryString["id"] as string;
#region Create Cache object
ICacheManager _objYear = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objMonth = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objDepartment = CacheFactory.GetCacheManager();//Create cache object
ICacheManager _objSection = CacheFactory.GetCacheManager();//Create cache object
#endregion
if (Request.QueryString["ClickTag"]!=null)
{
#region set Cached items
if (Request.QueryString["ClickTag"].ToString() == "1")
{
if (_objYear.Contains("Year"))
{
string _Year = (string)_objYear.GetData("Year");
ddlYear.SelectedValue = _Year;
}
if (_objMonth.Contains("Month"))
{
string _Month = (string)_objMonth.GetData("Month");
ddlMonth.SelectedValue= _Month;
}
if (_objDepartment.Contains("Department"))
{
string _Department = (string)_objDepartment.GetData("Department");
ddldepartment.SelectedValue= _Department;
}
if (_objSection.Contains("Section"))
{
string _Section = (string)_objSection.GetData("Section");
ddlSection.SelectedValue = _Section;
}
}
#endregion
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(ddlMonth.SelectedValue))
{
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
ddldepartment_SelectedIndexChanged(null, null);
ddlemp_SelectedIndexChanged(null, null);
if (ddlSection.SelectedIndex > 0)
ddlSection_SelectedIndexChanged(null, null);
}
}
void GetPeriods(int _year)
{
IBLCalenderPeriod _bl = (IBLCalenderPeriod)SetupBLFactory.GetCalenderPeriod();
DataSet _ds = (DataSet)_bl.GetPeriodIdsByYear(_year).GetMaster();
_ds.Tables[0].Columns.Add("ID");
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
_dr["ID"] = _dr["CLP_ID"] + "," + _dr["clp_activeperiod"] + "," + _dr["CLP_DATESTART"] + "," + _dr["CLP_DATEEND"] + "";
}
ddlMonth.DataSource = _ds.Tables[0];
ddlMonth.DataTextField = "CLP_DESCRIPTION";
ddlMonth.DataValueField = "ID";
ddlMonth.DataBind();
foreach (DataRow _dr in _ds.Tables[0].Rows)
{
if (_dr["clp_activeperiod"] != null)
if (_dr["clp_activeperiod"].ToString() == "1")
{
ddlMonth.SelectedValue = _dr["ID"].ToString();
hClpid.Value = ddlMonth.SelectedValue.Split(',')[0];
Session["Startdate"] = ddlMonth.SelectedValue.Split(',')[2];
Session["EndDate"] = ddlMonth.SelectedValue.Split(',')[3];
break;
}
else
{
ddlMonth.SelectedIndex = 0;
hClpid.Value = "0";
}
}
}
I think you are setting a value in ddlMonth but ddlMonth do not have that binded value.. Try to bind list of values in your ddlMonth before setting a value to it
Please next time format the code before posting.
For the problem I think the solution is to put the region where you set the SelectedValue inside an
if(!isPostback){...}
I suggest you to take a look to the documentation about page lifecycle, because the explanation is that the Page_Load in executed not only the first time you load a page, but also for every postback (if you don't use the if(!isPostback){...}
i am working on a project and i have a gridview and a radiobutton in gridview and what i want is,i want to send the selected rows value to database on the click of the button but i am getting an error as object reference not set to the instance of an object.
As my code is
cs code on the click of the button
protected void btn_selectgridview_Click(object sender, EventArgs e)
{
int k = 0;
//Checkther whether atleast one check box is selected or not
for (int i = 0; i <=gvrepair_details.Rows.Count-1; i++)
{
GridViewRow row = gvrepair_details.Rows[i];
RadioButton rb = (RadioButton)row.FindControl("CheckBox1");
if (rb.Checked == true)
{
k++;
}
}
if (k == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(),Guid.NewGuid().ToString(), "<script language=JavaScript>alert('select the value in grid');</script>");
return;
}
for (int i = 0; i <=gvrepair_details.Rows.Count-1; i++)
{
string bookname = gvrepair_details.Rows[i].Cells[1].Text;
string categoryname = gvrepair_details.Rows[i].Cells[2].Text;
string subcategory =gvrepair_details.Rows[i].Cells[3].Text;
string shelf_no = gvrepair_details.Rows[i].Cells[4].Text;
string isbn = gvrepair_details.Rows[i].Cells[5].Text;
string edition = gvrepair_details.Rows[i].Cells[6].Text;
string status = gvrepair_details.Rows[i].Cells[7].Text;
GridViewRow row = gvrepair_details.Rows[i];
RadioButton rb = (RadioButton)row.FindControl("CheckBox1");
if (rb.Checked == true)
{
InsertData(bookname, categoryname, subcategory, shelf_no, isbn, edition, status);
}
}
}
void InsertData(String bookname, String categoryname, String subcategory,String shelf_no,String isbn,String edition,String status)
{
try
{
sql = "insert into library_repair(bookname, categoryname, subcategoryname, shelf_no, isbn, edition, status)values('" +bookname+ "','" +categoryname+ "','" +subcategory+ "','"+shelf_no+"','"+isbn+"','"+edition+"','"+status+"')";
ds = obj.openDataset(sql, Session["SCHOOLCODE"].ToString());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
I reformulated you first function (Code may contains syntax error since haven't run it):
protected void btn_selectgridview_Click(object sender, EventArgs e)
{
int k = 0;
int checkBoxColumnIndex = 2; //Here you should specify the cell containing the checkBox
foreach (GridViewRow item in gvrepair_details.Rows)
{
RadioButton rb = (RadioButton)item.Cells[checkBoxColumnIndex].FindControl("CheckBox1");
if (rb != null && rb.Checked) //Check if rb is null
{
k++;
string bookname = item.Cells[1].Text;
string categoryname = item.Cells[2].Text;
string subcategory = item.Cells[3].Text;
string shelf_no = item.Cells[4].Text;
string isbn = item.Cells[5].Text;
string edition = item.Cells[6].Text;
string status = item.Cells[7].Text;
InsertData(bookname, categoryname, subcategory, shelf_no, isbn, edition, status);
}
}
//Checkther whether atleast one check box is selected or not
if (k == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script language=JavaScript>alert('select the value in grid');</script>");
return;
}
}
Note the checkBoxColumnIndex. CheckBox1 index should be provided.
try this
if (((RadioButton)gvrepair_details.Rows[i].FindControl("CheckBox1")).Checked == true)
{
k++;
}
instead of
if (rb.Checked == true)
{
k++;
}
Project_Detail pro = new Project_Detail();
string title=Ttitle.Text;
string year1=Tyear.Text;
string key = Tkeywrds.Text;
string area = Ddl_area.Text;
string categ = Ddl_catgry.Text;
string tech = Ddl_tech.Text;
string type =Ddl_type.Text;
var q = from obj in da.Project_Details
where obj.Project_Title.Contains(title)
|| obj.Submission_Date.Contains(year1)
|| obj.Keywords.Contains(key)
|| obj.Project_Area.Contains(area)
|| obj.Project_Category.Contains(categ)
|| obj.Project_Technology.Contains(tech)
|| obj.Project_Type.Contains(type)
select obj;
if (q != null)
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
this code give last record of table and also not give else condition result.
I want result of all condition and want to use LIke satatement.
q is never null. It might be empty, though. So you should change your code to
if (q.Any()) // <<-----
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
You can also use count method .Count()
if (q.count()>0)
{
DetailsView1.DataSource = q;
DetailsView1.DataBind();
}
else
{
Literal1.Text = "Data not found";
}
ok i have a project which has many gridview in its pages... now i am sorting the fridveiw using the sorting function like this:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["TaskTable2"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = Session["TaskTable2"];
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection2 = "ASC";
// Retrieve the last column that was sorted.
string sortExpression2 = ViewState["SortExpression2"] as string;
if (sortExpression2 != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression2 == column)
{
string lastDirection = ViewState["SortDirection2"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection2 = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection2"] = sortDirection2;
ViewState["SortExpression2"] = column;
return sortDirection2;
}
but this code is being repeated in many pages so i tried to put this function in a C# class and try to call it but i get errors....
for starters i get the viewstate error saying :|
"viewstate does not exist in the current context"
so how do i go about doing this ....??
thanks
so this is what is there in my class:
public string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection2 = "ASC";
// Retrieve the last column that was sorted.
string sortExpression2 = ViewState["SortExpression2"] as string;
if (sortExpression2 != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression2 == column)
{
string lastDirection = ViewState["SortDirection2"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection2 = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection2"] = sortDirection2;
ViewState["SortExpression2"] = column;
return sortDirection2;
}
and i am calling it from my code like this:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = Session["TaskTable2"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + new impersonateClass().GetSortDirection(e.SortExpression);
GridView1.DataSource = Session["TaskTable2"];
GridView1.DataBind();
}
}
and i get view state error...
is here a way to put this entire thing in the class... because it is getting repeated everywhere...
You will need to pass the ViewState in, as the ViewState object is a member of the Page class. Once you moved the code into a separate class, it no longer had access to the ViewState object.
public string GetSortDirection(string column, StateBag viewState) {
// Your code here.
}