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){...}
Related
I want to output values inside the class object to the console. Here's my code. This won't work. There is no error, but this won't output the values.
This is my method.
public ClsPayeDetails get_paydetail_byrow(int rowno)
{
string sql = "SELECT * FROM s07_01_payeDetails WHERE row_no='"+rowno+"'";
DataRow dr = LogIn.HR_Connection.GetSingleRow(sql);
ClsPayeDetails obj_det = null;
if (dr != null)
{
obj_det = new ClsPayeDetails(
decimal.Parse(dr["reducing_value"].ToString()),
dr["financial_year"].ToString(),
decimal.Parse(dr["lower_limit"].ToString()),
decimal.Parse(dr["upper_limit"].ToString()),
decimal.Parse(dr["percentage"].ToString())
);
}
Console.WriteLine(obj_det.ToString());
return obj_det;
}
// and this is where i call it. I think i'm doing this in incorrect way. //Any help would be appreciated.
private void testDetToolStripMenuItem_Click(object sender, EventArgs e)
{
cc_payroll.pyrl_cls_master.ClsPayeDetails dd = new cc_payroll.pyrl_cls_master.ClsPayeDetails();
dd.get_paydetail_byrow(1);
}
change your code
Console.WriteLine(obj_det.ToString());
to
Console.WriteLine(obj_det.getXXXXXXX().ToString());
getXXXXXXX() is your attribute in the class ClsPayeDetails.
ToString() function designed to return the value of 'single value object' like int, string... etc else it returns the object type.
So you need to:
Overwrite the function Tostring() in your class'ClsPayeDetails' to return a value not the type
Get object's properties and its values automatically.
you can use this code as it's or return any other string you want.
public override string ToString()
{
string result = "";
foreach (System.Reflection.PropertyInfo p in this.GetType().GetProperties())
{
if (!string.IsNullOrEmpty(result)) result += Environment.NewLine;
result += p.Name + ": " + p.GetValue(this);
}
return result;
}
You can use override string ToString function in your ClsPayeDetails class
public class ClsPayeDetails
{
//Your property class
public override string ToString()
{
System.Text.StringBuilder val = new System.Text.StringBuilder();
val.Append(string.Format("reducing_value = {0},", reducing_value));
val.Append(string.Format("financial_year = {0},", financial_year));
val.Append(string.Format("lower_limit = {0},", lower_limit));
val.Append(string.Format("upper_limit = {0},", upper_limit));
val.Append(string.Format("percentage = {0},", percentage));
return val.ToString();
}
}
This solved my problem. I changed my method go static and then accessed by class.
private void testDetToolStripMenuItem_Click(object sender, EventArgs e)
{
cc_payroll.pyrl_cls_master.ClsPayeDetails dd = ClsPayeDetails.get_paydetail_byrow(2);
Console.WriteLine(dd.FinancialYear.ToString());
Console.WriteLine(dd.lowerLimit.ToString());
Console.WriteLine(dd.upperLimit.ToString());
Console.WriteLine(dd.percenTage.ToString());
Console.WriteLine(dd.adjust.ToString());
}
and the method is
public static ClsPayeDetails get_paydetail_byrow(int rowno)
{
string sql = "SELECT * FROM s07_01_payeDetails WHERE row_no='" + rowno + "'";
DataRow dr = LogIn.HR_Connection.GetSingleRow(sql);
ClsPayeDetails obj_det = null;
if (dr != null)
{
obj_det = new ClsPayeDetails(
decimal.Parse(dr["reducing_value"].ToString()),
dr["financial_year"].ToString(),
decimal.Parse(dr["lower_limit"].ToString()),
decimal.Parse(dr["upper_limit"].ToString()),
decimal.Parse(dr["percentage"].ToString())
);
}
else
{
MessageBox.Show("This row does not exist !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return obj_det;
}
I'm trying to access a certain variable from another class, however I'm not able to do so. I have two buttons - the first button sets token to an html template file. The second should generate the file. The first button calls the class. The second button should call the string from the class for generation.
My first button is as follows:
private void btnTemplate_Click(object sender, EventArgs e)
{
if ((txtTitle.Text == "") && (txtSku.Text == "") && (txtPrice.Text == "") && (txtDesc.Text == "") && (txtImg.Text == ""))
{
MessageBox.Show("No row selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
OpenFileDialog SetData = new OpenFileDialog();
SetData.Filter = "HTML|*.html;";
GlobalVar.setPath = "C:\\genHtml.html";
var result = SetData.ShowDialog();
DataSet ds = new DataSet();
if (result == DialogResult.OK)
{
string fileName = SetData.FileName;
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);
}
}
}
My second button:
private void btnGenerate_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(GlobalVar.setPath);
}
catch
{
MessageBox.Show("Please select a template first", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I get an error with the string output. How can I call string 'output' for the second button?
My class is as follows:
class HtmlTemplate
{
private string _html;
public HtmlTemplate(string templatePath)
{
using (var reader = new StreamReader(templatePath))
_html = reader.ReadToEnd();
}
public string Render(object values)
{
string output = _html;
foreach (var p in values.GetType().GetProperties())
output = output.Replace("[" + p.Name + "]", (p.GetValue(values, null) as string) ?? string.Empty);
return output;
}
}
There is not enough context to be sure, but in the case of the second button it looks like output is not declared as a variable or possibly not assigned a (correct) value.
File.WriteAllText(#GlobalVar.setPath, output);
could become
var template = new HtmlTemplate(#SetData.FileName);
File.WriteAllText(#GlobalVar.setPath, template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
or alternatively
var template = new HtmlTemplate(#SetData.FileName);
var output = template.Render(new
{
TITLE = txtTitle.Text,
SKU = txtSku.Text,
PRICE = txtPrice.Text,
DESC = txtDesc.Text,
IMAGE = txtImg.Text
});
File.WriteAllText(#GlobalVar.setPath, output);
I am trying to View a report dynamically from code behind. But when the parameters are changed from dynamic textboxes added in the page. in the report refresh() the data is not changed.
I call sqlDS() and reportBuild() in the !IsPostback.
This method is for defining the sqlDatasource:
protected void sqlDS()
{
string conString, prName = "";
int counter = 0;
Reporting rep = new Reporting();
rep = rep.searchReport(repID_HF.Value);
Reporting repFold = new Reporting();
repFold = repFold.searchFolder(foldID_HF.Value);
if (repFold.FolderName.Split('(')[1] == "Web Reports)")
{
conString = dbSql.connectionStringAll;
prName = dbSql.providerName;
}
else
{
conString = db.connectionStringAll;
prName = db.providerName;
}
SqlDataSource1.ConnectionString = conString;
SqlDataSource1.ProviderName = prName;
string sqlString = System.IO.File.ReadAllText(Server.MapPath("~/Reports/SQLs/" + rep.SqlFile));
sqlString.Replace(System.Environment.NewLine, " ");
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.CancelSelectOnNullParameter = false;
Reporting repParam = new Reporting();
allPs = repParam.getAllParamRep(rep.RepID);
foreach (Reporting itemParam in allPs)
{
if (itemParam.ParamType == "Date")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Text")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Menu")
{
counter++;
}
}
}
This method is for declaring the report properties:
protected void reportBuild()
{
Reporting rep2 = new Reporting();
rep2 = rep2.searchReport(repID_HF.Value);
ReportViewer1.LocalReport.ReportPath = "Reports/RDLC/" + rep2.RdlcFile;
this.ReportViewer1.LocalReport.ReportEmbeddedResource = rep2.RdlcFile;
ReportParameter[] paramss = new ReportParameter[SqlDataSource1.SelectParameters.Count];
for (int i = 0; i < SqlDataSource1.SelectParameters.Count; i++)
{
paramss[i] = new ReportParameter(SqlDataSource1.SelectParameters[i].Name.Split(':')[1], SqlDataSource1.SelectParameters[i].DefaultValue);
}
ReportDataSource rds = new ReportDataSource(rep2.DatasetName.Split('.')[0], SqlDataSource1);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
//paramss[0] = new ReportParameter("TDATE", SqlDataSource1.SelectParameters[0].DefaultValue);
//paramss[1] = new ReportParameter("CUST_NUM", SqlDataSource1.SelectParameters[1].DefaultValue);
ReportViewer1.LocalReport.SetParameters(paramss);
ReportViewer1.LocalReport.Refresh();
}
In the reportViewer refresh method i try to set the new parameters according to the dynamic textboxes added in the page:
protected void ReportViewer1_ReportRefresh(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (Control txt in Panel1.Controls)
{
if (txt is TextBox)
{
txts.Add(txt);
}
}
foreach (TextBox txtbox in txts)
{
Reporting repP = new Reporting();
repP = repP.searchParam(txtbox.Attributes["pID"].ToString());
if (repP.ParamType == "Date")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
else if (repP.ParamType == "Text")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
}
//Reporting r = new Reporting();
//r = r.searchReport(repID_HF.Value);
//Reporting rep = new Reporting();
//rep = rep.searchReport(repID_HF.Value);
//ReportDataSource rds = new ReportDataSource(rep.DatasetName.Split('.')[0], SqlDataSource1);
//this.ReportViewer1.Reset();
//ReportViewer1.LocalReport.DataSources.Clear();
//ReportViewer1.LocalReport.DataSources.Add(rds);
ReportParameterInfoCollection x = ReportViewer1.LocalReport.GetParameters();
//Response.Redirect(Request.RawUrl);
ReportViewer1.LocalReport.Refresh();
}
I tried debugging and found every thing is working correctly the SQL parameters changed, the Report Parameters also is changed.
so why the data in the report is not changed? Plz help me
I got a better and easier way to solve this problem using this link
http://www.igregor.net/post/2007/12/Adding-Controls-to-an-ASPNET-form-Dynamically.aspx
And you can use array of strings to pass attributes.
i am using a datagridview in that i am using a datagridviewcomboboxcolumn, comboboxcolumn is displaying text but the problem is i want to select the first item of comboboxcolumn by default how can i do this
DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
i++;
}
The values available in the combobox can be accessed via items property
row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];
the best way to set the value of a datagridViewComboBoxCell is:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as
DataRowView).Row[1].ToString();
}
It worked with me very well
If I had known about doing it in this event, it would have saved me days of digging and
trial and errors trying to get it to set to the correct index inside the CellEnter event.
Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!!
In reviewing all the issues other coders have been experiencing with trying to set
the index inside of a DataGridViewComboBoxCell and also after looking over your code,
all that anyone really needs is:
1. Establish the event method to be used for the "EditingControlShowing" event.
2. Define the method whereby it will:
a. Cast the event control to a ComboBox.
b. set the "SelectedIndex" to the value you want.
In this example I simply set it to "0", but you'd probably want to apply so real life logic here.
Here's the code I used:
private void InitEvents()
{
dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );
}
private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
{
ComboBox ocmb = e.Control as ComboBox;
if ( ocmb != null )
{
ocmb.SelectedIndex = 0;
}
}
If DataGridViewComboBoxCell already exist:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item 1", "0");
dt.Rows.Add("Item 2", "1");
dt.Rows.Add("Item 3", "2");
dt.Rows.Add("Item 4", "3");
for (int i = 0; i < dvg.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
comboCell.DisplayMember = "Item";
comboCell.ValueMember = "Value";
comboCell.DataSource = dt;
};
I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. However, here is what I ended up with:
public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
{
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = dataSource;
if (cbx.Value == null)
{
if(dataSource.Count > 0)
{
T m = (T)cbx.Items[0];
FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
cbx.Value = fi.GetValue(m);
}
}
}
It basically sets the .Display and .ValueMember properties of the DataGridViewComboBoxCell and uses a List as DataSource. It then takes the first item, and uses reflection to get the value of the member that was used as ValueMember and sets the selected value via .Value
Use it like this:
public class Customer
{
private String name;
public String Name
{
get {return this.name; }
set {this.name = value; }
}
private int id;
public int Id
{
get {return this.id; }
set {this.id = value; }
}
}
public class CustomerCbx
{
private String display;
public String Display
{
get {return this.display; }
set {this.display = value; }
}
private Customer value;
public Customer Value
{
get {return this.value; }
set {this.value = value; }
}
}
public class Form{
private void Form_OnLoad(object sender, EventArgs e)
{
//init first row in the dgv
if (this.dgv.RowCount > 0)
{
DataGridViewRow row = this.dgv.Rows[0];
DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];
Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
List<CustomerCbx> custList = new List<CustomerCbx>()
{
new CustomerCbx{ Display = c1.Name, Value = c1},
new CustomerCbx{ Display = c2.Name, Value = c2},
}
InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
}
}
}
}
It seems pretty hacky to me, but I couldn't find any better way so far (that also works with complex objects other than just Strings). Hope that will save the search for some others ;)
You need to set the Items for the new cell. This must be auto done by the column when creating a new row from the UI.
var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});
something different worked for me what i did is to simply set the value of dtataGridComboBox when ever new record is added bu user with 'userAddedRow' event. For the first row I used the code in constructor.
public partial class pt_drug : PatientDatabase1_3._5.basic_templet
{
public pt_drug()
{
InitializeComponent();
dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
}
private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
}
}
Here the solution I have found : select the cell you are interested in so you can cast it to a combobox.
this.Invoke((MethodInvoker)delegate
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
this.dataGridView1.BeginEdit(true);
ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
comboBox.SelectedIndex += 1;
});
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.
}