I am accesing value from database and displaying them on form ,i have successfully displayed retrived value in textbox and radiobox but i am not able to display them in combbox .
In combox items I have values(1 2 3 4) in this combox i want to display fetched value from database for eg. i accesed value 4 for combbox then it should display 4 value selected in it .
how could i achieve this?
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('~');
txtQuestion.Text = coldata[1];
txtOption1.Text = coldata[2];
txtOption2.Text = coldata[3];
txtOption3.Text = coldata[4];
txtOption4.Text = coldata[5];
string a = coldata[6];
if (a == "1")
{
radioButton1.Checked = true;
}
else if (a == "2")
{
radioButton2.Checked = true;
}
else if (a == "3")
{
radioButton3.Checked = true;
}
else if (a == "4")
{
radioButton4.Checked = true;
}
cmbMarks.ValueMember = coldata[7];//in cmbMarks.ValueMember i am getting fetched value but it is not displaying in combbox ,where i am wrong?
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
Thanks in Advance for any help
cmbMarks.Text = coldata[7].Substring(1)
See this MSDN page. The .Substring(1) is assuming that coldata[7] is a string with a $ as the first character.
Related
I am retrieving data from db and displaying in Label. but the problem is that this cannot retrieve db tabel first row data. Its print Second row data. If i given the db first row c_code then it is given the Error "There is no row at position 2" Kindly please solve my problem.
Thanks you
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)
{
var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (var_C_Code.Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I believe this is probably the issue:
for (int i = 0; i <= dt_C_Code.Rows.Count; ; i++) {...}
Please consider substituting foreach (DataRow row in dt_C_Code.Rows) { ...}
If it's important which row should logically come "first", then please consider using an order by clause in your SQL statement.
Now problem is solve the problem is that break key word.
private void Get_Purchasing_Amount()
{
try
{
string get_P_Amount = "";
double var_P_Amount = 0;
//int var_C_Code = 0;
string query = "select c_code as 'code' from `db_vegetable`.`tbl_payment_master`";
DataTable dt_C_Code = method_Class.method_Class.FetchRecords(query);
if (dt_C_Code.Rows.Count > 0)
{
for (int i = 0; i <= dt_C_Code.Rows.Count; i++)//these line generate error please check this
{
//var_C_Code = Convert.ToInt32(dt_C_Code.Rows[i]["code"]);
if (Convert.ToInt32(dt_C_Code.Rows[i]["code"]).Equals(Convert.ToInt32(txt_Customer_Code.Text)))
{
if (check_All.Checked.Equals(true))
{
get_P_Amount = "SELECT IFNULL(`purchasing`,0) AS 'purchasing' FROM `db_vegetable`.`tbl_payment_master` WHERE `c_code` = " + txt_Customer_Code.Text + "";
}
else
{
string dt_Query = "select `id` as 'id' from `db_vegetable`.`tbl_order_details`";
DataTable dt_C_O = method_Class.method_Class.FetchRecords(dt_Query);
if (dt_C_O.Rows.Count > 0)
get_P_Amount = "SELECT IFNULL(SUM(t_price),0) as 'purchasing' FROM `db_vegetable`.`tbl_order_details` WHERE `c_code` = " + txt_Customer_Code.Text + " AND (`date` BETWEEN '" + txt_From_Date.Text + "' AND '" + txt_To_Date.Text + "')";
else
lbl_Purchasing_Amount.Text = "0";
}
DataTable dt = method_Class.method_Class.FetchRecords(get_P_Amount);
var_P_Amount = Convert.ToDouble(dt.Rows[0]["purchasing"]);
lbl_Purchasing_Amount.Text = var_P_Amount.ToString();
break;
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
}
else
{
lbl_Purchasing_Amount.Text = "0";
}
}
catch (Exception)
{
}
}
I want to fetch some data from two different tables PRO and OPN_STK , in some controls like textboxs and datagridview . when i am selecting data from one table i.e. PRO ,the code is working perfect but when i applied same code just next to it , in same event for fetching data from another table i.e. OPN_STK it throws exception "object refrence not set to an instance of object" . I tried to know about the problem but now I'm blank , this is what I did ,
private void comboProname_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
//if (get == false) //in case when i need to apply condition which I dont prefer
{
string _sql = "select DISTINCT P_batchno,P_sh from PRO where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
//else if (get == true) // opnstk
{
string _sql = "select DISTINCT P_batchno,P_sh from OPN_STK where P_name='" + comboProname.Text + "'";
if (comboBthNo.Text != "")
_sql += " AND P_batchno='" + comboBthNo.Text + "' ";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboBthNo.Text == "")
{
dataGridView3.Visible = true;
int i = 0;
dataGridView3.Rows.Insert(i);
dataGridView3.Rows[i].Cells[0].Value = dr["P_batchno"].ToString();
dataGridView3.Focus();
}
sh = dr["P_sh"].ToString();
}
}
getdata();
}
private void comboBthNo_TextChanged(object sender, EventArgs e)
{
dataGridView3.Rows.Clear();
dataGridView2.Rows.Clear();
// if (get == false)
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from PRO where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows)
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
// else if (get == true) ///// opn stk ///////
{
string _sql = "SELECT DISTINCT P_name,P_pack,P_comp,P_expdate,P_rate,P_mrp from OPN_STK where P_batchno='" + comboBthNo.Text + "'";
if (comboProname.Text != "")
_sql += " AND P_name='" + comboProname.Text + "'";
if (SampleToggle)
_sql += " AND IsSample='true' ";
else
_sql += " AND IsSample='false' ";
DataTable dt = DataBase.getDataTable(_sql);
foreach (DataRow dr in dt.Rows) // I get exception here only on dt
{
if (comboProname.Text == "")
{
dataGridView2.Visible = true;
int i = 0;
dataGridView2.Rows.Insert(i);
dataGridView2.Rows[i].Cells[0].Value = dr["P_name"].ToString();
dataGridView2.Focus();
}
tbMrp.Text = (dr["P_mrp"].ToString());
dateTimePicker2.Text = (dr["P_expdate"].ToString());
}
}
getdata();
}
i would appriciate any help ,thanks in advance .
Put a breakpoint in your code, debug and check that OPN_STK is not null. If it is null that would be your problem.
I have a registration application for a Windows Surface Tablet PC.
It works brilliantly but there's one more thing i need to work:
The registration works by either being in an Online State(For a Staff Register), or an Offline State(For Student Event Registrations).
When it's in its Online State, we scan barcodes in to it which holds 6 digits + 'L' , which goes to the database and pulls out the Staff Members name and 6 digit code, then it will list the Staff Members name in order down the listbox.
What i am looking to do is List the time it was first entered into the application, and then when they scan the same code again, instead of removing the first entry it will add another time onto the existing line, such as:
First Scan:
Ryan Gillooly (123456) Time: 11:40
Second Scan:
Ryan Gillooly (123456) Time: 11:40 Time: 13:26
and so on and so forth.
Here is the code :
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
if (listBox1.Items.Contains(returnValue))
{
for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
string removelistitem = returnValue.ToString();
if (listBox1.Items[n].ToString().Contains(removelistitem))
{
//listBox1.Items.Add(" " + "\t Time:" + " " + DateTime.Now.ToString("HH.mm"));
listBox1.Items.RemoveAt(n);
}
}
}
else
listBox1.Items.Add(returnValue + "\t Time:" + " " + DateTime.Now.ToString("HH.mm"));
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
SaveFile.WriteLine(item.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
}
Try something like this:
.....
DBConnection.Close();
bool found=false;
foreach (var item in listBox1.Items)
{
var entry = item.ToString();
if (entry.Contains(returnvalue.ToString()))
{
listBox1.Items.Remove(item);
listBox1.Items.Add(entry + " extra add");
found = true;
break;
}
}
if (!found)
{
listBox1.Items.Add(returnvalue.ToString());
}
textBox1.Clear();
.....
UPDATE
Regarding your extra question in the comments:
You could use string.LastIndexOf to see which word was added last: "In" or "Out".
And then you take the other.
LastIndexOf returns the index of the last occurence of the searchstring, or -1 when it's not present.
Out of my mind you would get something like:
private string CreateNewEntry(string current)
{
var indexIn = current.LastIndexOf("in"); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("out"); // Get the last index of the word out
if (indexOut > indexIn)
{
return current + " in "; // if the last "out" comes after the last "in"
}
else
{
// If the last "in" comes after the last "out"
return current + " out ";
}
}
This will return the current entry + " in " or " out ".
Anbd then you just have to add your extra stuff to it.
To call this, replace the Add-sentences with:
listBox1.Items.Add(CreateNewEntry(entry) + " extra stuff");
hi I am trying to load data into sql from an excel spreadsheet from a web page, I am getting a "Cannot implicitly convert type 'string' to 'decimal" error I have tried different ways to correct this but nothing is working.
namespace CarpartsStore.Dealers
{
partial class DealerHome : System.Web.UI.Page
{
protected void ButtonUpload_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = true;
PanelView.Visible = false;
PanelImport.Visible = false;
}
protected OleDbCommand ExcelConnection()
{
// Connect to the Excel Spreadsheet
string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;";
// create your excel connection object using the connection string
OleDbConnection objXConn = new OleDbConnection(xConnStr);
objXConn.Open();
// use a SQL Select command to retrieve the data from the Excel Spreadsheet
// the "table name" is the name of the worksheet within the spreadsheet
// in this case, the worksheet name is "Members" and is coded as: [Members$]
OleDbCommand objCommand = new OleDbCommand("SELECT * FROM [Products$]", objXConn);
return objCommand;
}
protected void ButtonView_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = false;
PanelView.Visible = true;
PanelImport.Visible = false;
// Create a new Adapter
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter();
// retrieve the Select command for the Spreadsheet
objDataAdapter.SelectCommand = ExcelConnection();
// Create a DataSet
DataSet objDataSet = new DataSet();
// Populate the DataSet with the spreadsheet worksheet data
objDataAdapter.Fill(objDataSet);
// Bind the data to the GridView
GridViewExcel.DataSource = objDataSet.Tables[0].DefaultView;
GridViewExcel.DataBind();
}
protected void ButtonImport_Click(object sender, System.EventArgs e)
{
PanelUpload.Visible = false;
PanelView.Visible = false;
PanelImport.Visible = true;
LabelImport.Text = "";
// reset to blank
// retrieve the Select Command for the worksheet data
OleDbCommand objCommand = new OleDbCommand();
objCommand = ExcelConnection();
// create a DataReader
OleDbDataReader reader;
reader = objCommand.ExecuteReader();
// create variables for the spreadsheet columns
int ProductID = 0;
int MakeID = 0;
int DealerID = 0;
string PartNumber = "";
string Description = "";
decimal UnitCost = 0.00M;
decimal Postage = 0.00M;
int QtyAvailable = 0;
string UserName = "";
string Make = "";
int counter = 0;
// used for testing your import in smaller increments
while (reader.Read())
{
counter = counter + 1;
// counter to exit early for testing...
// set default values for loop
ProductID = 0;
MakeID = 0;
DealerID = 0;
PartNumber = GetValueFromReader(reader,"PartNumber");
Description = GetValueFromReader(reader,"Description");
UnitCost = GetValueFromReader(reader,"UnitCost");
Postage = GetValueFromReader(reader, "Postage");
QtyAvailable = GetValueFromReader(reader,"QtyAvailable");
UserName = GetValueFromReader(reader,"UserName");
Make = GetValueFromReader(reader,"Make");
// Insert any required validations here...
MakeID = GetMakeID(Make);
DealerID = GetDealerID(UserName);
//retrieve the MakeID
ProductID = ImportIntoProducts(PartNumber, Description, UnitCost, Postage, QtyAvailable, MakeID, DealerID);
LabelImport.Text = LabelImport.Text + ProductID + PartNumber + " " + Description + " " + UnitCost + " " + Postage + " " + QtyAvailable + " " + UserName + " Make_id: " + MakeID + " " + Make + "<br>";
//If counter > 2 Then ' exit early for testing, comment later...
// Exit While
//End If
}
reader.Close();
}
protected string GetValueFromReader(OleDbDataReader myreader, string stringValue)
{
object val = myreader[stringValue];
if (val != DBNull.Value)
return val.ToString();
else
return "";
}
protected void ButtonUploadFile_Click(object sender, System.EventArgs e)
{
if (FileUploadExcel.HasFile)
{
try
{
// alter path for your project
FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls"));
LabelUpload.Text = "Upload File Name: " +
FileUploadExcel.PostedFile.FileName + "<br>" +
"Type: " + FileUploadExcel.PostedFile.ContentType +
" File Size: " + FileUploadExcel.PostedFile.ContentLength +
" kb<br>";
}
catch (System.NullReferenceException ex)
{
LabelUpload.Text = "Error: " + ex.Message;
}
}
else
{
LabelUpload.Text = "Please select a file to upload.";
}
}
protected int GetMakeID(string MakeName)
{
int makeID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter();
SSSProductsDataSet.MakesDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetMakeByName(MakeName);
// see if the category already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].MakeID > 0)
{
makeID = SSDataTable[0].MakeID;
}
}
}
if (makeID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key category_id from the insert
makeID = (int)SSAdapter.InsertMakeQuery(MakeName);
// if this fails to return the proper category_id, make sure to
// set the InsertCategoryQuery ExecuteMode Property to Scalar
}
return makeID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + ex.Message;
return 0;
}
}
protected int GetDealerID(string UserName)
{
int DealerID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter();
SSSProductsDataSet.DealersDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetDealersByUserName(UserName);
// see if the User already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].DealerID > 0)
{
DealerID = SSDataTable[0].DealerID;
}
}
}
if (DealerID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key category_id from the insert
DealerID = 0;
// if this fails to return the proper category_id, make sure to
// set the InsertCategoryQuery ExecuteMode Property to Scalar
}
return DealerID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + ex.Message;
return 0;
}
}
protected int ImportIntoProducts(string PartNumber, string Description, decimal UnitCost, decimal Postage, int QtyAvailable, int MakeID, int DealerID)
{
// make sure values don't exceed column limits
PartNumber = Left(PartNumber, 50);
Description = Left(Description, 300);
UnitCost = Convert.ToDecimal(UnitCost);
int ProductID = 0;
try
{
CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter();
SSSProductsDataSet.ProductsDataTable SSDataTable = null;
SSDataTable = SSAdapter.GetProductsByPartNumberDealer(PartNumber, DealerID);
// see if the category already exists in the table, if not insert it
if (SSDataTable != null)
{
if (SSDataTable.Rows.Count > 0)
{
if (SSDataTable[0].ProductID > 0)
{
ProductID = SSDataTable[0].ProductID;
LabelImport.Text = LabelImport.Text + "<font color=blue>PartNumber Found, Not Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + "" + UnitCost + "" + Postage + ".</font><br>";
}
}
}
if (ProductID == 0)
{
// if it is still 0, then insert it into the table
// retrieve the identity key ProductID from the insert
ProductID = Convert.ToInt32(SSAdapter.InsertProductQuery(PartNumber, Description,UnitCost, Postage, QtyAvailable, MakeID, DealerID));
LabelImport.Text = LabelImport.Text + "<font color=white>Part Number Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + " Cost: " + UnitCost + ".</font><br>";
}
return ProductID;
}
catch (System.NullReferenceException ex)
{
LabelImport.Text = LabelImport.Text + "<font color=red>" + ex.Message + "</font><br>";
return 0;
}
}
// http://www.mgbrown.com/PermaLink68.aspx
public static string Left(string text, int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException("length", length, "length must be > 0");
else if (length == 0 || text.Length == 0)
return "";
else if (text.Length <= length)
return text;
else
return text.Substring(0, length);
}
}
}
The following code change will allow your code to run:
try
{
UnitCost = GetValueFromReader(reader,"UnitCost");
}
catch(Exception)
{
// put a breakpoint here to find the problem using the debugger
}
try
{
Postage = GetValueFromReader(reader, "Postage");
}
catch(Exception)
{
// put a breakpoint here to find the problem using the debugger
}
What you really want to do is understand how the source data is causing the error. (Maybe you have a null or a non-numeric value in the source data.)
Leaving the code like this could (and probably will) introduce data errors into other parts of your system.
I have a function like this
///
/// This function binds the emplist drop down for mentor user.
///
private void BindEmpDropDownForMentor()
{
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
OleDbConnection oleConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
OleDbCommand oleCommand = new OleDbCommand(strSelectMentorQuery, oleConnection);
try
{
//Open Connection
oleConnection.Open();
//Set Datasource and close connection
cmbempList.DataSource = oleCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
cmbempList.DataValueField = "";
cmbempList.DataTextField = "NAME";
//Bind the Dropdown
cmbempList.DataBind();
//Add a new item 'ALL TEAM MEMBERS' to the member list
cmbempList.Items.Insert(0, new ListItem("ALL TEAM MEMBERS", "0"));
cmbempList.SelectedIndex = 0;
GridViewDataShowBy = cmbempList.SelectedValue;
}
catch (Exception ex)
{
ExceptionLogger.LogException(ex);
}
finally
{
// Close the connection when done with it.
oleConnection.Close();
}
}
But on selected change event of cmbempList, format exception error is being caught saying this that input string was not in correct form in the bold line below
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
gvLeaveList.CurrentPageIndex = 0;
dgDaysAbsent.CurrentPageIndex = 0;
**if (!(Convert.ToInt32(cmbempList.SelectedValue) > 0))
{**
if (this.Session["RoleID"].ToString() == "1")
{
cmbLeads.ClearSelection();
cmbLeads.SelectedIndex = cmbLeads.Items.IndexOf(cmbLeads.Items.FindByValue(this.Session["UserID"].ToString()));
}
}
GridViewDataShowBy = cmbempList.SelectedValue.ToString();
if (cmbempList.SelectedValue != "0" && cmbempList.SelectedValue != "")
{
Page.Title = cmbempList.SelectedItem.Text + " | Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
else
{
Page.Title = "Leave List | "
+ OrganizationManager.GetCurrentOrganizationName(Session["OrgID"]);
}
PopulateLeaveList(GridViewDataShowBy, "0");
BindLeaveListGrid(GridViewDataShowBy, cmbLeads.SelectedValue.ToString());
}
It is because cmbempList's DataValueField is being set to an empty string in the BindEmpDropDownForMentor method.
cmbempList.DataValueField = "";
This will cause cmbempList's values to be bound to the values in the DataTextField which are strings. When the SelectedIndexChange event is called it tries to parse the strings to an Int32 which is throwing the exception.
Convert.ToInt32(cmbempList.SelectedValue) > 0
To fix it you can add an aliased ID field in the SQL query and set the cmbempList.DataValueField to that ID name which is probably your intent.
For example in BindEmpDropDownForMentor make this edit to your query:
string strSelectMentorQuery = "SELECT FIRST_NAME + ' ' + LAST_NAME AS NAME, MLL.LED_ID AS ID FROM M_USER_DETAILS MUD INNER JOIN M_LEADERLED MLL "
+ "ON MLL.LED_ID = MUD.PK_ID WHERE MLL.LEADER_ID = '" + Session["UserID"].ToString()
+ "' AND MUD.ACTIVE = 1 AND MLL.START_DATE <= Getdate() AND"
+ " MLL.END_DATE > Getdate()";
And assign your DataValueField to this:
cmbempList.DataValueField = "ID";
try this.
if it still fails look in the debugger what value cmbempList.SelectedValue contains.
protected void cmbempList_SelectedIndexChanged(object sender, EventArgs e)
{
// ...
object selectedValue = cmbempList.SelectedValue;
if ((selectedValue != null) && (selectedValue != DBNull.Value) && (!(Convert.ToInt32(selectedValue) > 0))
{
// ...