Inserting Selected value from Gridview to Mysql database - c#

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++;
}

Related

ListItem.Selected returning false

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

TableAdapter.Update don't update

I tried to add data from data set to access database with TableAdapter.Update() method, but it doesn't function. Here is my code. I have DataGridView on my Windows Form, Table (Users) are binding to DataGridView.
private void btnScanGroups_Click(object sender, EventArgs e)
{
foreach (UserGroup group in g)
{
string groupName = group.Name;
string groupID = group.Link;
int userID = 1;
groupsTableAdapter.InsertGroupsQuery(groupName, groupID, userID);
text = text+"\n added "+groupName + " - " + groupID;
richTxtBoxStatus.Text = text;
}
groupsTableAdapter.Fill(facebookGroupAutoPostDBDataSet.Groups);
groupsBindingSource.EndEdit();
groupsTableAdapter.Update(facebookGroupAutoPostDBDataSet.Groups);
}

How do i change a label to match the selected index of a combo box?

Here i have some code that works fine. Except the thing i need it do the most right now.
I have a label which i've named (lblProfileID) and i need this label to display the (ProfileID) that matches the (ProfileName) depending on the selection i've made in the combobox where all the Profilenames are stored.
How do i accomplish this task?
public void QueriesProfile()
{
QueryResult queryResultProfile = null;
String SOQL = "";
SOQL = "Select Id, Name from Profile";
queryResultProfile = Sfdcbinding.query(SOQL);
string profileID = null;
string ProfileName = null;
if (queryResultProfile.size > 0)
{
for (int i = 0; i < queryResultProfile.size; i++)
{
Profile userProfile = (Profile)queryResultProfile.records[i];
profileID = userProfile.Id;
ProfileName = userProfile.Name;
string[] uSersProfile = { ProfileName, profileID };
listProfile.AddRange(uSersProfile);
cmbProfile.Items.Add(ProfileName);
lblProfileID.Text = cmbProfile.SelectedIndex(profileID); /// <--- How do i do this?
}
}
}
public void QueriesProfile()
{
cmbProfile.SelectedIndexChanged+=cmbProfile_SelectedIndexChanged;
QueryResult queryResultProfile = null;
String SOQL = "";
SOQL = "Select Id, Name from Profile";
queryResultProfile = Sfdcbinding.query(SOQL);
string profileID = null;
string ProfileName = null;
if (queryResultProfile.size > 0)
{
for (int i = 0; i < queryResultProfile.size; i++)
{
Profile userProfile = (Profile)queryResultProfile.records[i];
profileID = userProfile.Id;
ProfileName = userProfile.Name;
string[] uSersProfile = { ProfileName, profileID };
listProfile.AddRange(uSersProfile);
cmbProfile.Items.Add(ProfileName);
}
}
}
private void cmbProfile_SelectedIndexChanged(object sender, EventArgs e)
{
lblProfileID.Text = cmbProfile.SelectedIndex(profileID);
}

Index (zero based) must be greater than or equal to zero and less than the size of the argument list while inserting the arraylist

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?

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){...}

Categories