How to call a procedure if the procedure does not have parameter - asp.net

create proc sp_dropdown
as
begin
SELECT r1.regid, r.registration
FROM table1 as r1
INNER JOIN table2 as r ON r1.regid=r.registration and r1.status=r.status
end

this above class is my sp return type,
public class GetAllTableNames_Result
{
public string Name { get; set; }
}
and i can call this like
public List<GetAllTableNames_Result> GetTableNames()
{
List<GetAllTableNames_Result> gatnr = new List<GetAllTableNames_Result>();
SqlCommand cmd = new SqlCommand(
"GetAllTableNames", _connection) {CommandType = CommandType.StoredProcedure};
try
{
_connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//do something with data
gatnr.Add(new GetAllTableNames_Result()
{
Name = rdr[0].ToString()
});
}
_connection.Close();
return gatnr;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
_connection.Close();
}
}
i believe you can get point

Related

"Cannot implicitly convert type 'Lab06.Attendance' to 'System.Collections.Generic.List<Lab06.Attendance>" How to solve this error

AssignmentAttendance.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Description;
namespace Lab06 {
public partial class AssignmentAttendance : System.Web.UI.Page
{
Attendance aAttendance = new Attendance();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}
protected void bind()
{
List<Attendance> attendancelist = new List<Attendance>();
attendancelist = aAttendance.getAttendanceAll();
GridView1.DataSource = attendancelist;
GridView1.DataBind();
}
protected void Retrieve_Attendance_Click(object sender, EventArgs e)
{
string attributename = tb_classcode.ToString();
List<Attendance> attendanceList = new List<Attendance>();
attendanceList = aAttendance.getAttendance(attributename);
GridView1.DataSource = attendanceList;
GridView1.DataBind();
}
/* protected void edit_attendance(object sender, GridViewEditEventArgs e)
{
}*/
}
}
AssignmentContentUploadClass.cs
public class Attendance {
string _connStr =ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString;
private string _ClassCode = null;
private string _Teacher_ID = "";
private string _TeachingSessions = "";
private string _Remarks = "";
public Attendance()
{
}
// Constructor that take in all data required to build a Product object
public Attendance(string ClassCode, string Teacher_ID, string TeachingSessions, string Remarks)
{
_ClassCode = ClassCode;
_Teacher_ID = Teacher_ID;
_TeachingSessions = TeachingSessions;
_Remarks = Remarks;
}
public string ClassCode
{
get { return _ClassCode; }
set { _ClassCode = value; }
}
public string Teacher_ID
{
get { return _Teacher_ID; }
set { _Teacher_ID = value; }
}
public string TeachingSessions
{
get { return _TeachingSessions; }
set { _TeachingSessions = value; }
}
public string Remarks
{
get { return _Remarks; }
set { _Remarks = value; }
}
public int createAttendance()
{
int result = 0;
string queryStr = "INSERT INTO Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks)"
+ " values (#ClassCode, #Teacher_ID, #TeachingSessions, #Remarks)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", this.ClassCode);
cmd.Parameters.AddWithValue("#Teacher_ID", this.Teacher_ID);
cmd.Parameters.AddWithValue("#TeachingSessions", this.TeachingSessions);
cmd.Parameters.AddWithValue("#Remarks", this.Remarks);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}//end Insert
public Attendance getAttendance(string ClassCode)
{
Attendance attendanceDetail = null;
string Teacher_ID, TeachingSessions, Remarks;
string queryStr = "Select * From Attendance Where ClassCode = #ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#ClassCode", ClassCode);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
attendanceDetail = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
}
else
{
attendanceDetail = null;
}
conn.Close();
dr.Close();
dr.Dispose();
return attendanceDetail;
}
public List<Attendance> getAttendanceAll()
{
List<Attendance> attendancelist = new List<Attendance>();
string ClassCode, Teacher_ID, TeachingSessions, Remarks;
string queryStr = "SELECT * FROM Attendance Order By ClassCode";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ClassCode = dr["ClassCode"].ToString();
Teacher_ID = dr["Teacher_ID"].ToString();
TeachingSessions = dr["TeachingSessions"].ToString();
Remarks = dr["Remarks"].ToString();
Attendance a = new Attendance(ClassCode, Teacher_ID, TeachingSessions, Remarks);
attendancelist.Add(a);
}
conn.Close();
dr.Close();
dr.Dispose();
return attendancelist;
}
}
I am not sure of the error and thus I am not able to provide much
I am trying use the getAttendance(ClassCode) function to retrieve the data based off my input of my classcode in the textbox of my AssignmentAttendance.aspx.
I am thinking of using the getAttendance function in my AssignmentAttendance.aspx file by passing in the data of my classcode entry from the textbox to retrieve the details of the Attendance based off classcode.
However, I am not too sure how that works and might need some help
My database has:
ClassCode
Teacher_ID
TeachingSessions
Remarks
If anything is missing or I did not make things clear do let me know
-Edit-
I am getting an error from my AssignmentAttendance.aspx.cs file
attendanceList = aAttendance.getAttendance(attributename);

Populating a dropdown list from the database c# aspx

I am struggling a bit to populate my dropdown list, can anybody tell me where I am going wrong?
ASPX CODE it keeps looping after getting the connection string - back into the connection string method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private string GetConnectionString()
{
using (DataManager dmgr = new DataManager())
{
dmgr.Connect(ConfigurationManager.AppSettings["ProductionKey"]);
return BindDropDownList();
}
}
public string BindDropDownList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Itemseriesmaster";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Description"; // the items to be displayed in the list items
DropDownList1.DataValueField = "ID"; // the id of the items displayed
DropDownList1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return AppRelativeTemplateSourceDirectory;
}
DataManager Code - where the code calls into
public DataSet ItemSeriesMaster(int id, string description)
{
object[] args = new object[2] { id, description };
return CallSp(MethodBase.GetCurrentMethod(), args) as DataSet; // i know this is not an sp call.. just testing
}
}
}
I am trying to go to my database and bring out the list.

Transaction Management in asp.net

I am doing a web application in asp.net.
I have a class CommonDB to save data.
public class CommonDB
{
private static string GetConnectionString = ConfigurationManager.ConnectionStrings["Db"].ToString();
public static SqlConnection GetConnection()
{
SqlConnection Con = new SqlConnection(GetConnectionString);
if (Con.State == ConnectionState.Open)
{
Con.Close();
}
return Con;
}
public static int ExecuteNonquery(SqlCommand cmd)
{
SqlConnection Con = GetConnection();
Con.Open();
try
{
cmd.Connection = Con;
Con.Close();
return ReturnVal;
}
catch
{
Con.Close();
return 0;
}
}
}
}
I am using the following function to save data
public int AddGroupMaster() //Inserting
{
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "NV_Group_Master_Add";
cmd.Parameters.AddWithValue("#Group_ID", iGroupId);
cmd.Parameters.AddWithValue("#Group_Code", strGroupName);
cmd.Parameters.AddWithValue("#Group_Name", strGroupName);
cmd.Parameters.AddWithValue("#Created_On", strCreatedOn);
cmd.Parameters.AddWithValue("#Modified_On", strModifiedOn);
iReturn = CommonDB.ExecuteNonquery(cmd);
return iReturn;
}
catch { return 0; }
}
This function is called from code behind like :
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
objGroup.strGroupName = txtGroupName.Text.Trim();
objGroup.strCreatedOn = DateTime.Today.ToString();
objGroup.strModifiedOn = "";
objGroup.AddGroupMaster();
}
catch
{
}
}
I want to use Commit and rollback. How it is possible in my coding??
Please suggest a solution
In your scenario, you will have to do that in your CommonDB library.
For example, your ExecuteNonQuery method would look like this:
public static int ExecuteNonquery(SqlCommand cmd) {
int retVal;
SqlConnection Con = GetConnection();
DbTransaction tran;
try {
cmd.Connection = Con;
cmd.Connection.Open();
tran = cmd.Connection.BeginTransaction;
cmd.Transaction = tran;
retVal = cmd.ExecuteNonQuery;
tran.Commit()
} catch {
tran.Rollback();
throw;
} finally {
cmd.Connection.Close()
}
return retVal;
}
And yes, do not forget to get a reference to System.Data.Common.

Arithmetic operation resulted in an overflow

After updating my website on ii7 on window server 2008 from framework 3.5 to work with framework 4
i got my c# base database class stop working copmlitly with this error: "Arithmetic operation resulted in an overflow".
I am working with mysql server from different server.
I did not find any solution on this so i had very sadness to role bakce to framework 3.5
here is some of my logs for this error in the event viewr on my server:
Process information:
Process ID: 3680
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: OverflowException
Exception message: Arithmetic operation resulted in an overflow.
at DataAccess.ExecuteStringQuery(String strSQL) in d:\webSites\s2s\App_Code\DB\DataAccess.cs:line 214
at DataSelect.generalString(String rowName, String tableName, String idName, String ID) in d:\webSites\s2s\App_Code\DB\DataSelect.cs:line 48
at camsBaseShowWeb.OnPreInit(EventArgs e) in d:\webSites\s2s\App_Code\Bases\camsBaseShowWeb.cs:line 134
at System.Web.UI.Page.PerformPreInit()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
big thanks for any halp
i got this error - no matter wich function i try to call from this code
here is my code:
using System;
using System.Data;
//using Microsoft.Data.Odbc;
using System.Data.Odbc;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public class DataAccess
{
#region Private Variables
private static DataAccess _DataAccess = null;
private static object _SyncLock = new object();
private string _strCon = "Driver={MySQL ODBC 5.1 Driver};Server=theIP;Database=theDatabase; UID=root;Password=thePassword;Option=3;";
private OdbcConnection myConnection = null;
#endregion
#region Instance Method
public static DataAccess Instance
{
get
{
lock (_SyncLock)
{
if (_DataAccess == null)
_DataAccess = new DataAccess();
return _DataAccess;
}
}
}
#endregion
#region Constractors
public DataAccess()
{
myConnection = new OdbcConnection(_strCon);
myConnection.Open();
}
#endregion
#region Public Functions
public OdbcDataReader ExecuteQueryReader(string strSQL)
{
try
{
OdbcCommand myCommand = new OdbcCommand(strSQL, myConnection);
return myCommand.ExecuteReader();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQueryReader SQL s2s", strSQL, ex);
}
throw ex;
}
}
public DataTable ExecuteQuery(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public DataView ExecuteQueryDV(string strSQL)
{
DataTable dt = new DataTable();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(dt);
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return new DataView(dt);
}
public DataTable ExecuteLimitedQuery(string strSQL, int startRow, int rowNum)
{
DataTable dt;
DataSet ds = new DataSet();
OdbcDataAdapter objDataAdapter = null;
try
{
objDataAdapter = new OdbcDataAdapter(strSQL, myConnection);
objDataAdapter.Fill(ds, startRow, rowNum, "rowTable");
dt = (DataTable)ds.Tables["rowTable"];
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteLimitedQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (objDataAdapter != null) objDataAdapter.Dispose();
}
return dt;
}
public object ExecuteScalarQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteScalarQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj;
}
public string ExecuteStringQuery(string strSQL)
{
OdbcCommand myCommand = null;
object obj = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex)
{
if (myConnection.State != ConnectionState.Open)
{
myConnection.Open();
if (myCommand != null) myCommand.Dispose();
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
obj = myCommand.ExecuteScalar();
}
catch (Exception ex2)
{
if (Dict.IsRemote == true)
{
sendMail("error - לאחר ניסיון שני ExecuteStringQuery SQL s2s", strSQL, ex2);
}
throw ex2;
}
}
else
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteStringQuery SQL s2s", strSQL, ex);
}
throw ex;
}
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return obj != null ? obj.ToString() : string.Empty;
}
public int ExecuteNoneQuery(string strSQL)
{
OdbcCommand myCommand = null;
int i;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
i = myCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error ExecuteNoneQuery SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return i;
}
public int InsertGetLastID(string strSQL)
{
OdbcCommand myCommand = null;
int LastID = 0;
object objID = null;
try
{
myCommand = new OdbcCommand(strSQL, myConnection);
if (myCommand.ExecuteNonQuery() == 1)
{
myCommand = new OdbcCommand("SELECT LAST_INSERT_ID()", myConnection);
objID = myCommand.ExecuteScalar();
if (objID != null)
{
LastID = int.Parse(objID.ToString());
}
}
}
catch (Exception ex)
{
if (Dict.IsRemote == true)
{
sendMail("error InsertGetLastID SQL s2s", strSQL, ex);
}
throw ex;
}
finally
{
if (myCommand != null) myCommand.Dispose();
}
return LastID;
}
private void sendMail(string title, string sql, Exception ex)
{
string body = string.Empty +
"SQL:\n\n" + sql + "\n\n" +
"Exeption:\n\n" + ex.Message + "\n\n" +
"Stack Trace:\n\n" + ex.StackTrace + "\n\n" +
"Source:\n\n" + ex.Source + "\n\n";
mailSend mailS = new mailSend("theMail", "mailTo", title, body);
}
#endregion
}
I was getting this too since the upgrade to .Net 4.0
System.OverflowException: Arithmetic operation resulted in an overflow.
at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcCommand.ExecuteScalar()
at Server.Engines.MyRunUO.DatabaseCommandQueue.Thread_Start() in d:\RunUO\Sec
ondAge\Scripts\Engines\MyRunUO\DatabaseCommandQueue.cs:line 117
OdbcConnection version is System.Data.dll, v4.0.30319
Using "{MySQL ODBC 5.1 Driver}" (actually 5.01.06.00) against MySQL 5.1.40-community via TCP/IP on localhost.
The query was any variation of:
SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='chardb'
The (apparently) offending lines:
command.CommandText = string.Format("SELECT COUNT(*) FROM myrunuo_timestamps WHERE time_type='{0}'", m_timeStampName); // Line 116
object result = command.ExecuteScalar(); // Line 117
This occurred with an x64 compile only, i.e. using the x64 mySQL driver.
This was fixed by upgrading from mySQL ODBC driver 5.01.06.00 to 5.01.08.00
conver to boolean function does not work when
1. Development is done on 32 bit OS
2. Implementation is done on 64 bit OS
When I altered the code for Convert.ToBoolean function, It worked normally.

asp.net sql or collection problem

following is the code on Placementsearch.aspx.cs
protected void Ok_Click(object sender, EventArgs e)
{
try
{
if (Page.IsValid)
{
int course_id = Convert.ToInt32(course.SelectedValue);
int passoutYear = Convert.ToInt32(passout.SelectedValue);
int currentBacklog = Convert.ToInt32(currrentBacklogDDL.SelectedValue);
int sex = Convert.ToInt32(gender.SelectedValue);
int? eGap = null;
int? firstYrPercent = null;
int? secondYrPercent = null;
int? thirdYrPercent = null;
int? finalYearpercent = null;
int? currentDegeePercentage = null;
int? highSchoolPercentge = null;
int? higherSchoolPercentage = null;
int? grauationPercentage = null;
int? diplomaPercentage = null;
int? noOfAtkt = null;
DateTime? date = null;
if (!string.IsNullOrEmpty(DOB.Text.Trim()))
{
string dateOfBirth = DOB.Text.Trim();
DateTime birthDate = DateTime.ParseExact(dateOfBirth, "dd/mm/yyyy", System.Globalization.CultureInfo.InvariantCulture);
string outPut = birthDate.ToString("mm/dd/YYYY");
date = Convert.ToDateTime(outPut);
}
if (!String.IsNullOrEmpty(educationGap.Text.Trim()))
{
eGap = Convert.ToInt32(educationGap.Text.Trim());
}
if (!string.IsNullOrEmpty(firstYear.Text))
{
firstYrPercent = Convert.ToInt32(firstYear.Text.Trim());
}
if (!string.IsNullOrEmpty(secondYear.Text.Trim()))
{
secondYrPercent = Convert.ToInt32(secondYear.Text.Trim());
}
if (!string.IsNullOrEmpty(thirdYear.Text))
{
thirdYrPercent = Convert.ToInt32(thirdYear.Text.Trim());
}
if (!string.IsNullOrEmpty(finalyear.Text.Trim()))
{
finalYearpercent = Convert.ToInt32(finalyear.Text.Trim());
}
if (!string.IsNullOrEmpty(currentDegree.Text.Trim()))
{
currentDegeePercentage = Convert.ToInt32(currentDegree.Text.Trim());
}
if (!string.IsNullOrEmpty(higherSchool.Text.Trim()))
{
higherSchoolPercentage = Convert.ToInt32(higherSchool.Text.Trim());
}
if (!string.IsNullOrEmpty(highSchool.Text.Trim()))
{
highSchoolPercentge = Convert.ToInt32(highSchool.Text.Trim());
}
if (!string.IsNullOrEmpty(graduation.Text.Trim()))
{
grauationPercentage = Convert.ToInt32(graduation.Text.Trim());
}
if (!string.IsNullOrEmpty(diploma.Text.Trim()))
{
diplomaPercentage = Convert.ToInt32(diploma.Text.Trim());
}
if (!string.IsNullOrEmpty(atkt.Text.Trim()))
{
noOfAtkt = Convert.ToInt32(atkt.Text.Trim());
}
Dictionary<string, object> paramList = new Dictionary<string, object>();
paramList.Add("#courseId", course_id);
paramList.Add("#passoutYear", passoutYear);
paramList.Add("#currentBacklog", currentBacklog);
paramList.Add("#sex", sex);
paramList.Add("#eGap", eGap);
paramList.Add("#firstYrPercent", firstYrPercent);
paramList.Add("#secondYrPercent", secondYrPercent);
paramList.Add("#thirdYrPercent", thirdYrPercent);
paramList.Add("#finalYearpercent", finalYearpercent);
paramList.Add("#currentDegeePercentage", currentDegeePercentage);
paramList.Add("#highSchoolPercentge", highSchoolPercentge);
paramList.Add("#higherSchoolPercentage", higherSchoolPercentage);
paramList.Add("#grauationPercentage", grauationPercentage);
paramList.Add("#diplomaPercentage", diplomaPercentage);
paramList.Add("#noOfAtkt", noOfAtkt);
paramList.Add("#date", date);
StringBuilder branchId= new StringBuilder();
foreach (ListItem li in branch.Items)
{
if (li.Selected)
{
branchId.Append(Convert.ToInt32(li.Value));
}
}
DataTable dt = searchManager.GetEligibleStudent(paramList, branchId);
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error On Button click Ok", ex);
}
this is the method which is called from above page. this method is on class searchstudentDAO.cs
public DataTable GetEligibleStudent(Dictionary<string, object> paramList, StringBuilder branchId)
{
try
{
string cmd = #"SELECT * FROM [tbl_students] WHERE course_id=#courseId
AND branch_id IN(" + branchId + #")
AND (#firstYrPercent is null OR first_year_percent>=#firstYrPercent)
AND (#secondYrpercent is null OR second_year_percent>=#secondYrPercent)
AND (#thirdYrPercent is null OR third_year_percent>=#thirdYrPercent)
AND (#finalYearpercent is null OR final_year_percent>=#finalYearpercent)
AND (#currentDegeePercentage is null OR current_degree_percent>=#currentDegeePercentage)
AND (#passoutYear is null OR passing_year>=#passoutYear)
AND (#currentBacklog is null OR current_backlog<=#currentBacklog)
AND gender=#sex
AND (#eGap is null OR gapin_education<=#eGap)
AND (#highSchoolPercentge is null OR highschool_percentage>=#highSchoolPercentge)
AND (#higherSchoolPercentage is null OR ssc_percentage>=#higherSchoolPercentage)
AND (#grauationPercentage is null OR graduation_percentage>=#grauationPercentage)
AND (#diplomaPercentage is null OR diploma_percentage>=#diplomaPercentage)
AND (#noOfAtkt is null OR number_of_ATKT<=#noOfAtkt)
AND (#date is null OR DOB>=#date)";
//string cmd = "SELECT * FROM [tbl_branch] WHERE course_id IN(" + sb + ")";
if (dbManager.OpenConnection())
{
dt = dbManager.GetDataTable(cmd, paramList);
return dt;
}
else
{
dt = null;
return dt;
}
}
catch (Exception ex)
{
COMMON.logger.Error("Error ON Method Getting Eligible Students:SearchStudentDAO", ex);
dt = null;
return dt;
throw;
}
finally
{
dbManager.CloseConnection();
}
}
And followin is code called from the above method on paage App_Code/DBManager.cs
public DataTable GetDataTable(string strCmd, Dictionary<string, object> paramList)
{
try
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(strCmd, _sqlCon);
foreach (KeyValuePair<string, object> kvp in paramList)
{
cmd.Parameters.AddWithValue(kvp.Key, kvp.Value);
}
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
logger.Error("Error when executing Query " + strCmd, ex);
throw;
return null;
}
}
Now i am getting exception for those null parameter which are not provided
"Parameterized Query '(#courseId int,#passoutYear int,#currentBacklog int,#sex int,#eG' expects parameter #finalYearpercent, which was not supplied."
please correct me where i am wrong
Instead of simply not adding those parameters if they're null, you need to add them, but with the "value" set to DBNull.Value.

Resources