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.
}
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
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 getting this error:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at here:
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
ds.InsertPlan("1", splitItems[0], splitItems[1], splitItems[2],
splitItems[3], DateTime.Now, DateTime.Now, user, user, "Nil", 1));
And the C# code is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Specialized;
using System.Text;
public partial class Site_Allocation_Plan_Entry : System.Web.UI.Page
{
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("txtDate1");
tempDataTable.Columns.Add("txtPlace1");
tempDataTable.Columns.Add("txtPlace2");
tempDataTable.Columns.Add("txtDistance");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
GridView1.DataSource = tempDataTable;
GridView1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
DataRow tempRow = null;
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's TextBox values
var dateText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
var place1Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
var place2Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace2");
var distanceText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDistance");
// Create new row and update Row Number
tempRow = tempTable.NewRow();
tempTable.Rows[i - 1]["txtDate1"] = dateText.Text;
tempTable.Rows[i - 1]["txtPlace1"] = place1Text.Text;
tempTable.Rows[i - 1]["txtPlace2"] = place2Text.Text;
tempTable.Rows[i - 1]["txtDistance"] = distanceText.Text;
rowIndex++;
}
// Add data to datatable and viewstate
tempTable.Rows.Add(tempRow);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
GridView1.DataSource = tempTable;
GridView1.DataBind();
}
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 0; i < tempTable.Rows.Count; i++)
{
var dateText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
var place1Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
var place2Text =
(TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtPlace2");
var distanceText =
(TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDistance");
dateText.Text = tempTable.Rows[i]["txtDate1"].ToString();
place1Text.Text = tempTable.Rows[i]["txtPlace1"].ToString();
place2Text.Text = tempTable.Rows[i]["txtPlace2"].ToString();
distanceText.Text = tempTable.Rows[i]["txtDistance"].ToString();
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.SetInitialRowToGrid();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
deleteRow(index);
SetPreviousData();
}
private int deleteRow(int index)
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's TextBox values
var dateText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
var place1Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
var place2Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace2");
var distanceText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDistance");
}
// Add data to datatable and viewstate
tempTable.Rows.RemoveAt(index);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
GridView1.DataSource = tempTable;
GridView1.DataBind();
}
}
//Set Previous Data on Postbacks
return index;
}
protected void btnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["TempTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["TempTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtPlace2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDistance");
TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("txtDate1");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text + "," + box4.Text);
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
private void InsertRecords(StringCollection sc)
{
DS_SiteDataTableAdapters.tbl_planTableAdapter ds;
ds = new DS_SiteDataTableAdapters.tbl_planTableAdapter();
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
string user = Page.User.Identity.Name;
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}'); ", ds.InsertPlan("1", splitItems[0], splitItems[1], splitItems[2], splitItems[3], DateTime.Now, DateTime.Now, user, user, "Nil", 1));
}
}
try
{
//Display a popup which indicates that the record was successfully inserted
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
}
Any help will be greatly appreciated...
Your sb.AppendFormat format string expects 5 items.
You said ds.InsertPlan() has the following signature, and the arguments map to InsertPlan() not AppendFormat(). However, InsertPlan() returns a single int, so AppendFormat() only has 1 argument, an int value.
public virtual int InsertPlan(
string Plan_ID, <- "1"
string Place_1, <- splitItems[0]
string Place_2, <- splitItems[1]
string Distance, <- splitItems[2]
string Date, <- splitItems[3]
System.Nullable<System.DateTime> Created_Time, <- DateTime.Now
System.Nullable<System.DateTime> Updated_Time, <- DateTime.Now
string Created_by, <- user
string Updated_By, <- user
string Version_Status, <- "Nil"
System.Nullable<int> p3 <- 1
)
Your code:
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
ds.InsertPlan("1", // <-- unless InsertPlan() returns an array, then this
// is only 1 argument to the outer function
splitItems[0],
splitItems[1],
splitItems[2],
splitItems[3],
DateTime.Now, DateTime.Now, user, user, "Nil", 1
)
);
is like:
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
1); // only {0} has a argument
// {1} ... {4} do not
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){...}
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.