I have created a payment in Checks and Payments screen of Acumatica screen and released it. Please refer to the following screenshot.
I've already create the following code to provide it.
protected virtual void APPayment_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
string serverJade, dbJade, userJade, passJade;
serverJade = Properties.Settings.Default.serverJade;
dbJade = Properties.Settings.Default.dbJade;
userJade = Properties.Settings.Default.userJade;
passJade = Properties.Settings.Default.passJade;
APPayment app = (APPayment)e.Row;
if (e.Operation == PXDBOperation.Update && e.TranStatus == PXTranStatus.Completed)
{
if (app.DocType == APPaymentType.Check || app.DocType == APPaymentType.Prepayment)
{
if (app.RefNbr != null)
{
using (SqlConnection con = new SqlConnection("server = " + serverJade + "; database = " + dbJade + "; user = " + userJade + "; password = " + passJade + ""))
{
con.Open();
//---- query to update a field in the table of another database -------//
string query = "Update EVMaster set AcuRefNo = '" + app.RefNbr + "' where VchNo = 'DD02/16-VIII/12206-VCH-01'";
using (SqlCommand com = new SqlCommand(query, con))
{
SqlDataReader sdr = com.ExecuteReader();
sdr.Close();
}
con.Close();
}
}
}
}
}
I already tried to debug this code, but didn't work. And then I try to use this follwing code.
protected virtual void APPayment_RowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
string serverJade, dbJade, userJade, passJade;
serverJade = Properties.Settings.Default.serverJade;
dbJade = Properties.Settings.Default.dbJade;
userJade = Properties.Settings.Default.userJade;
passJade = Properties.Settings.Default.passJade;
APPayment app = (APPayment)e.Row;
if (app.DocType == APPaymentType.Check || app.DocType == APPaymentType.Prepayment)
{
if (app.RefNbr != null)
{
using (SqlConnection con = new SqlConnection("server = " + serverJade + "; database = " + dbJade + "; user = " + userJade + "; password = " + passJade + ""))
{
con.Open();
//---- query to update a field in the table of another database -------//
string query = "Update EVMaster set AcuRefNo = '" + app.RefNbr + "' where VchNo = 'DD02/16-VIII/12206-VCH-01'";
using (SqlCommand com = new SqlCommand(query, con))
{
SqlDataReader sdr = com.ExecuteReader();
sdr.Close();
}
con.Close();
}
}
}
}
The codes above is worked, I just remove the if condition (if (e.Operation == PXDBOperation.Update && e.TranStatus == PXTranStatus.Completed)
{}).
But it's not my goal, I have to filter document only for Doc Status = 'printed' from the document, and this process will be executed when 'Release' button was clicked.
And also any idea how to get all records in APAdjust of the current document ? because I need to comparing adjgrefnbr in apadjust with refnbr in APInvoice based on adjgrefnbr (apadjust) = refnbr (apinvoice). So I can get also all records of APinvoice based on refnbr (APinvoice) = ajgrefnbr (current apadjust). This condition is used to make 'where' condition of query not have to be hardcoded, I will used variable to provide it.
any suggestions to sove this problem ?
Below is an example showing how to extend Release process for checks and subscribe to RowPersisted handler for the APRegister DAC to save released document RefNbr to another database:
public class APPaymentEntryExt : PXGraphExtension<APPaymentEntry>
{
public PXAction<APPayment> release;
[PXUIField(DisplayName = "Release", MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Update)]
[PXProcessButton]
public IEnumerable Release(PXAdapter adapter)
{
PXGraph.InstanceCreated.AddHandler<APReleaseProcess>((graph) =>
{
graph.RowPersisted.AddHandler<APRegister>(APReleaseCheckProcess.APPaymentRowPersisted);
});
return Base.release.Press(adapter);
}
}
public class APReleaseChecksExt : PXGraphExtension<APReleaseChecks>
{
protected virtual void ReleaseChecksFilter_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
var row = e.Row as ReleaseChecksFilter;
if (row == null) return;
Base.APPaymentList.SetProcessDelegate(list =>
{
PXGraph.InstanceCreated.AddHandler<APReleaseProcess>((graph) =>
{
graph.RowPersisted.AddHandler<APRegister>(APReleaseCheckProcess.APPaymentRowPersisted);
});
APReleaseChecks.ReleasePayments(list, row.Action);
});
}
}
By executing quite simple BQL query you can access APAdjust records associated with released check within handler for the RowPersisted event:
public static class APReleaseCheckProcess
{
public static void APPaymentRowPersisted(PXCache sender, PXRowPersistedEventArgs e)
{
if (e.TranStatus == PXTranStatus.Completed && e.Operation == PXDBOperation.Update)
{
var doc = e.Row as APPayment;
if (doc != null && doc.Released == true)
{
// save RefNbr to another database
foreach (APAdjust oldadj in PXSelect<APAdjust,
Where<
APAdjust.adjgDocType, Equal<Required<APPayment.docType>>,
And<APAdjust.adjgRefNbr, Equal<Required<APPayment.refNbr>>,
And<APAdjust.adjNbr, Less<Required<APPayment.lineCntr>>>>>>
.Select(sender.Graph, doc.DocType, doc.RefNbr, doc.LineCntr))
{
}
}
}
}
}
Related
I am looking in my code if connected user has insert or update permission, stated in the SQL Server. If user has INSERT permission, editing previously saved records in table in datagridview is disabled, and only adding new rows is enabled. And if user has both INSERT or UPDATE permission, user can edit any records in table. My code works great if user has only INSERT permision but if he has both insert and update, i dont know how to cancel that if loop.
Here is my code for CellBeginEdit:
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
string db2 = Text1;
string user2 = Text2;
string pass2 = Text3;
string selected = this.ComboBox1.GetItemText(this.ComboBox1.SelectedItem);
using (SqlConnection SqlConn = new SqlConnection(#"Data Source=server;Initial Catalog =" + db2 + "; User ID =" + user2 + "; Password =" + pass2 + ""))
{
SqlConn.Open();
SqlCommand SqlCmd2 = new SqlCommand();
SqlCommand SqlCmd3 = new SqlCommand();
SqlCmd2.Connection = SqlConn;
SqlCmd3.Connection = SqlConn;
SqlCmd2.CommandText = "SELECT isnull(has_perms_by_name('" + db2 + ".dbo." + selected + "', 'OBJECT', 'INSERT'), 0)";
SqlCmd3.CommandText = "SELECT isnull(has_perms_by_name('" + db2 + ".dbo." + selected + "', 'OBJECT', 'UPDATE'), 0)";
Int32 number2 = (Int32)SqlCmd2.ExecuteScalar();
Int32 number3 = (Int32)SqlCmd3.ExecuteScalar();
if (number2 == 1)
{
if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
{
if (e.RowIndex < dataGridView1.NewRowIndex)
{
if (AddedRowIndex != e.RowIndex)
{
MessageBox.Show("Not allowed to edit previous records!");
e.Cancel = true;
}
}
}
}
else if ((number2 == 1) && (number3 == 1))
{
//enable editing of all records in table
}
SqlConn.Close();
}
}
The problem appears to be that you're checking for the more simple condition first, and it's going to be true for both Insert and Update, which means the else if condition is never checked and your enable-update code never runs.
Instead, you should check the compound condition first, and if that's false, then check the single condition.
For example:
if (number2 == 1 && number3 == 1)
{
// enable editing of all records
}
else if (number2 == 1)
{
// enable insert only
}
or another option, since they share a condition:
if (number2 == 1)
{
if (number3 == 1)
{
// enable editing of all records
}
else
{
// enable insert only
}
}
I am trying to make this code work fine as i can but i couldnt,i am using cookie and i want to rebind my ListView depending on cookie Location but i am getting error message: "Must declare the scalar variable "#Location"."
protected void Sortcarbtn_Click(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies.Get("Location");
using (SqlConnection carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString))
if (cookie != null)
{
string CarSqlST = #"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit,
SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads Where 1=1 AND Category=#CATE AND Country = #Location ";
var Location = Convert.ToString(cookie["Location"]);
var cat = Convert.ToString(Request.QueryString["cat"]);
string condition = "";
if (barndcardrlst.SelectedValue != "")
{
condition += " and Maker='" + barndcardrlst.SelectedValue + "'";
}
if (GearDrDw.SelectedValue != "")
{
condition += " and Gear='" + GearDrDw.SelectedValue + "'";
}
if (carstatedrdolst.SelectedValue != "")
{
condition += " and State='" + carstatedrdolst.SelectedValue + "'";
}
if (citiesdrdolst.SelectedValue != "")
{
condition += " and City='" + citiesdrdolst.SelectedValue + "'";
}
if (CarCondDrDw.SelectedValue != "")
{
condition += " and Condition='" + CarCondDrDw.SelectedValue + "'";
}
if (CarstusDRDL.SelectedValue != "")
{
condition += " and Status='" + CarstusDRDL.SelectedValue + "'";
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
condition += " and AdsPrice BETWEEN " + CarPriceFrmDrDw.SelectedValue + " AND " + CarPriceToDrDw.SelectedValue;
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
condition += " and Year BETWEEN " + CarYearfrmDrDw.SelectedValue + " AND " + CarYeartoDrDw.SelectedValue;
}
DataTable cdt = new DataTable();
carcon.Open();
SqlCommand ccmd = new SqlCommand();
ccmd.Connection = carcon;
ccmd.CommandType = CommandType.Text;
ccmd.Parameters.AddWithValue("#Country", Location);
ccmd.Parameters.AddWithValue("#CATE", cat);
ccmd.CommandText = CarSqlST + condition;
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
ad.Fill(cdt);
cateshowlistview.DataSource = cdt;
cateshowlistview.DataBind();
}
}
Change "#Country" in
ccmd.Parameters.AddWithValue("#Country", Location);
to be "#Location"
ccmd.Parameters.AddWithValue("#Location", Location);
you defined the Country in the SQL Statement to be #Location
string CarSqlST = #"SELECT ... AND Category=#CATE AND Country = #Location ";
Update
To prevent SQL Injection hacks and to allow for SQL to reuse the query options all the fileters where you are concat the string together you should just use SQL Parameters. To make it easy I create a parameters dictionary to add to. Then at the end loop through the dictionary to fill in the SQL Parameters. I also switched it to string builder since could be doing a lot of string concats. I didn't test this code because I don't have your objects or tables or connections.
using (var carcon = new SqlConnection(ConfigurationManager.ConnectionStrings["BeravaConnectionString"].ConnectionString)))
{
if (cookie != null)
{
// Parameters for SQL
var parameters = new Dictionary<string, object>();
// string builder to build up SQL Statement
var CarSqlST = new StringBuilder(
"SELECT DISTINCT AdsID, Section, Category, Country, Maker, Gear, Condition, Status, State, City, AdsTit, " +
"SUBSTRING(AdsDesc,1,155) as AdsDesc, Year, AdsPrice, Img1 From ads " +
"Where Category = #pCATE AND Country = #pLocation ");
parameters.Add("#pCATE", Request.QueryString["cat"].ToString());
parameters.Add("#pLocation", cookie["Location"]);
if (barndcardrlst.SelectedValue != "")
{
CarSqlST.Append(" and Maker= #pMaker");
parameters.Add("#pMaker", barndcardrlst.SelectedValue);
}
if (GearDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Gear= #pGear");
parameters.Add("#pGear", GearDrDw.SelectedValue);
}
if (carstatedrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pState");
parameters.Add("#pState", carstatedrdolst.SelectedValue);
}
if (citiesdrdolst.SelectedValue != "")
{
CarSqlST.Append(" and State= #pCity");
parameters.Add("#pCity", citiesdrdolst.SelectedValue);
}
if (CarCondDrDw.SelectedValue != "")
{
CarSqlST.Append(" and Condition= #pCondition");
parameters.Add("#pCondition", CarCondDrDw.SelectedValue);
}
if (CarstusDRDL.SelectedValue != "")
{
CarSqlST.Append(" and Status= #pStatus");
parameters.Add("#pStatus", CarstusDRDL.SelectedValue);
}
if ((CarPriceFrmDrDw.SelectedValue != "") && (CarPriceToDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and AdsPrice BETWEEN #pLowPrice AND #pHighPrice");
parameters.Add("#pLowPrice", CarPriceFrmDrDw.SelectedValue);
parameters.Add("#pHighPrice", CarPriceToDrDw.SelectedValue);
}
if ((CarYearfrmDrDw.SelectedValue != "") && (CarYeartoDrDw.SelectedValue != ""))
{
CarSqlST.Append(" and Year BETWEEN #pLowYear AND #pHighYear");
parameters.Add("#pLowYear", CarYearfrmDrDw.SelectedValue);
parameters.Add("#pHighYear", CarYeartoDrDw.SelectedValue);
}
DataTable cdt = new DataTable();
SqlCommand ccmd = carcon.CreateCommand();;
ccmd.CommandType = CommandType.Text;
// Add all the parameters into this command
foreach (var parameter in parameters)
{
ccmd.Parameters.Add(parameter.Key, parameter.Value);
}
// set the command text from string builder
ccmd.CommandText = CarSqlST.ToString();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = ccmd;
}
}
You could have created the command at the top and filled in the sql parameters right away instead of the dictionary but I like the dictionary approach better in case something happens - exception or we need to bail we never created the SQL Command.
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 written a custom class to handle database queries to a remote and local MySQL database, however when I do a nested loop I receive the below error:
MySql.Data.MySqlClient.MySqlException was unhandled
Message=There is already an open DataReader associated with this Connection which must be closed first.
Source=MySql.Data
ErrorCode=-2147467259
Number=0
My class currently looks like this
public class MySQLManager
{
private MySqlConnection _MySQLRemoteConnection { get; set; }
public void setup(string remoteUser, string remotePass, string remoteServerAddress, string remoteDb, string localUser, string localPass, string localServerAddress, string localDb)
{
_remote_server_address = remoteServerAddress;
_remote_database = remoteDb;
_remote_username = remoteUser;
_remote_password = remotePass;
}
public void connect()
{
try
{
_MySQLRemoteConnection = new MySqlConnection() { ConnectionString = string.Format("server={0};database={1};uid={2};password={3};", _remote_server_address, _remote_database, _remote_username, _remote_password) };
_MySQLRemoteConnection.Open();
_RemoteConnection = true;
}
catch (MySqlException ex)
{
_RemoteConnection = false;
}
}
public MySqlCommand run(string query, List<MySqlParameter> dbparams = null)
{
connect();
MySqlCommand sql = getConnection().CreateCommand();
sql.CommandText = query;
if (dbparams != null)
{
if (dbparams.Count > 0)
{
sql.Parameters.AddRange(dbparams.ToArray());
}
}
//disconnect();
return sql;
}
public MySqlDataReader fetch(MySqlCommand cmd)
{
//connect();
var t = cmd.ExecuteReader();
//disconnect();
return t;
}
And the code that I'm running to create the error, now I understand I can do the below example in a single query, this is an EXAMPLE query to re-create the error, writing it into a single query will not work with live examples.
query = "SELECT field1 FROM tmp WHERE field1 < 3";
using (var sql = db.run(query))
{
txtResponse.Text += "Query ran" + nl;
using (var row = db.fetch(sql))
{
txtResponse.Text += "Query fetched" + nl;
db.connect();
while (row.Read())
{
txtResponse.Text += "Row : " + row[0].ToString() + nl;
query = "SELECT val1 FROM tmp2 WHERE field1 = '" + row[0].ToString() + "'";
//db.disconnect();
using (var sql2 = db.run(query))
{
txtResponse.Text += "Query ran" + nl;
db.disconnect();
using (var row2 = db.fetch(sql))
{
txtResponse.Text += "Query fetched" + nl;
db.connect();
while (row.Read())
{
txtResponse.Text += " Val : " + row2[0].ToString() + nl;
}
}
}
}
}
}
So how would I go about getting the second loop to work?
For SQL Server, you could use MultipleActiveResultSets=true on connection string, but this most likely won't work for MySQL.
The other option is to use 2 connections, one for each data reader.
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))
{
// ...