I'm trying to put an ALL search function for my aspx page. The problem is that I have no idea how to do it properly. This is as far as I can go, here's the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtTransactionCategory = clsTransactionCategory.GetTransactionCategory(Helper.LogID, Helper.OrgID, Helper.SiteID, 0, string.Empty);
ddlTransactionCategoryDesc.DataSource = dtTransactionCategory;
ddlTransactionCategoryDesc.DataTextField = "TransactionCategoryDesc";
ddlTransactionCategoryDesc.DataValueField = "TransactionCategoryID";
ddlTransactionCategoryDesc.DataBind();
ddlTransactionCategoryDesc.Items.Insert(0, new ListItem("All"));
ddlTransactionCategoryInput.DataSource = dtTransactionCategory;
ddlTransactionCategoryInput.DataTextField = "TransactionCategoryDesc";
ddlTransactionCategoryInput.DataValueField = "TransactionCategoryID";
ddlTransactionCategoryInput.DataBind();
logID = CommonFunctions.StringToInt(Session[Constants.SessionLogID].ToString());
orgID = 1;
siteID = 1;
ddlTransactionCategoryDesc.SelectedValue = Convert.ToString(ddlTransactionCategoryDesc);
txtTransactionDesc.Text = string.Empty;
BindData();
}
}
and the stored procedure, should it needed:
ALTER PROC [dbo].[spMSTransaction_Get]
#OrgID INT,
#SiteID INT,
#TransactionCategoryID INT,
#TransactionCategoryDesc varchar (300),
#TransactionDesc varchar(300)
AS
SET NOCOUNT ON
SELECT mst.[OrgID],
mst.[SiteID],
mst.[TransactionID],
mst.[TransactionCategoryID],
mstc.[TransactionCategoryDesc],
mst.[TransactionDesc],
mst.[IsActive],
[master].dbo.fnConvertUTCToLocalTimeZone (mst.[CreatedDate]) as [CreatedDate],
mst.[CreatedBy],
[master].dbo.fnConvertUTCToLocalTimeZone (mst.[ModifiedDate]) as [ModifiedDate],
mst.[ModifiedBy]
FROM [dbo].[MSTransaction] AS mst
INNER JOIN [dbo].[MSTransactionCategory] AS mstc
ON mst.OrgID = mstc.OrgID AND mst.SiteID = mstc.SiteID AND mst.TransactionCategoryID = mstc.TransactionCategoryID
WHERE (mst.[OrgID] = #OrgID OR #OrgID = 0)
AND (mst.[SiteID] = #SiteID OR #SiteID = 0)
AND (mst.[TransactionCategoryID] = #TransactionCategoryID OR #TransactionCategoryID = 0)
AND (mst.[TransactionDesc] LIKE '%' + #TransactionDesc + '%')
AND (mst.[isActive] = 1)
I already put ddlTransactionCategoryDesc.Items.Insert(0, new ListItem("All")); but it returned an error:
Input string was not in a correct format.
Any idea what I need to fix and what I should do to make the ALL search function? Thanks.
According to your Stored Procedure, #TransactionCategoryID is an INT. Adding the ALL list will require you use the following instead:
ddlTransactionCategoryDesc.Items.Insert(0, new ListItem("All", "0"));
This will make the value of ALL to be an INT. What you currently have - ListItem("All") automatically changes the type of the Value to a string. Check your dropdown after execution, it will show the value as All but that cannot be passed into the INT that the Stored Proc requires.
Related
I try to count line in my SQL query.
It works without parameter. For example, if I assign directly FIOForm = 'SmithJJ'. I really don't understand what I'm doing wrong.
Exception: the SqlParameter is already contained by another SqlParameterCollection
int kolNar = 0;
System.Data.SqlClient.SqlParameter Name = new System.Data.SqlClient.SqlParameter("#Name", System.Environment.UserName);
var pushStat = db.Database.SqlQuery<Reestr>("select * from Reestr where FIOForm = #Name and Status = 'Executed'", Name);
foreach (var u in pushStat)
{
kolNar = pushStat.Count();
}
if (kolNar > 0)
MessageBox.Show(kolNar.ToString());
I suppose you can call:
Dispose();
before
System.Data.SqlClient.SqlParameter Name = new System.Data.SqlClient.SqlParameter("#Name", System.Environment.UserName);
I was getting a :There is no row at position 0 previously.On debugging i noticed the Count of Table Select_By_SNAME_BLOCKNO is 0 .
Also when i placed breakpoint ,on some columns i am getting Cannot evaluate expression because the code of the current method is optimized error .
So what is going wrong here?
Here is the block of code where error is received :
DS_HOUSE.HOUSE_SELECTDataTable HDT = new DS_HOUSE.HOUSE_SELECTDataTable();
DS_HOUSETableAdapters.HOUSE_SELECTTableAdapter HAdapter = new DS_HOUSETableAdapters.HOUSE_SELECTTableAdapter();
DS_USER.USERMST_SELECTDataTable UDT = new DS_USER.USERMST_SELECTDataTable();
DS_USERTableAdapters.USERMST_SELECTTableAdapter UAdapter = new DS_USERTableAdapters.USERMST_SELECTTableAdapter();
protected void Page_Load(object sender, EventArgs e)
{
lblsell.Text = "";
UDT = UAdapter.Select_By_UID(Convert.ToInt32(Session["uid"].ToString()));
HDT = HAdapter.Select_By_SNAME_BLOCKNO(UDT.Rows[0]["societyname"].ToString(), Convert.ToInt32(UDT.Rows[0]["HID"].ToString()));
ViewState["HID"] = HDT.Rows[0]["HID"].ToString();
lblbno.Text = HDT.Rows[0]["blockno"].ToString();
lbltype.Text = HDT.Rows[0]["type"].ToString();
lblsname.Text = HDT.Rows[0]["sname"].ToString();
Image3.ImageUrl = HDT.Rows[0]["image"].ToString();
}
Here is the defintion of Select_By_SNAME_BLOCKNO
public virtual DS_HOUSE.HOUSE_SELECTDataTable Select_By_SNAME_BLOCKNO(string sname, global::System.Nullable<int> bno) {
this.Adapter.SelectCommand = this.CommandCollection[5];
if ((sname == null)) {
this.Adapter.SelectCommand.Parameters[1].Value = global::System.DBNull.Value;
}
else {
this.Adapter.SelectCommand.Parameters[1].Value = ((string)(sname));
}
if ((bno.HasValue == true)) {
this.Adapter.SelectCommand.Parameters[2].Value = ((int)(bno.Value));
}
else {
this.Adapter.SelectCommand.Parameters[2].Value = global::System.DBNull.Value;
}
DS_HOUSE.HOUSE_SELECTDataTable dataTable = new DS_HOUSE.HOUSE_SELECTDataTable();
this.Adapter.Fill(dataTable);
return dataTable;
}
Also stored procedure Select_By_SNAME_BLOCKNO code is :
create procedure Select_By_SNAME_BLOCKNO
#sname nvarchar(50),
#bno int
AS
BEGIN
select * from dbo.HouseMst where Sname=#sname and blockno=#bno
This returns the values but i am not able to retrieve on page.
I have drop down and grid view..i fill drop down from database like this
There is two table tblReg and tblRes both have RegionID
protected void Page_Load(object sender, EventArgs e)
{
T1 tea = new T1();
var list1 = tea.tblReg.ToList();
var list = (from ta in list1
let data = ta.Region + " " + ta.StartDate ?? DateTime.Now.ToString() + " " + ta.EndDate ?? DateTime.Now.ToString()
select new { data, ta.RegionID }).ToList();
if(!Page.IsPostBack)
{
regiondrop.DataSource = list;
regiondrop.DataTextField = "data";
regiondrop.DataValueField = "RegionID";
regiondrop.DataBind();
}
}
now there is several values in drop down and i want when i select value from drop down then again to this value data will be display
On dropdown SelectedIndexChange i done this
protected void regiondrop_SelectedIndexChanged(object sender, EventArgs e)
{
T1 ts = new T1();
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==Convert.ToInt32(regiondrop.SelectedValue)
orderby dropdwn.OwnerName
select new {
FFID = dropdwn.FFID,
OwnerName = dropdwn.OwnerName,
RegNo = dropdwn.RegNo,
RegionID = dropdwn.RegionID,
});
GridView1.DataSource = dq;
GridView1.DataBind();
}
when i select value from dropdown it shows error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
on
GridView1.DataBind();
any solution
Well, as your error mentions, you can't do
Convert.ToInt32(regiondrop.SelectedValue)
in a linq to entities query (it can't be translated in sql / a store expression)
So just change these lines
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==Convert.ToInt32(regiondrop.SelectedValue)
to
var selectedValue = Convert.ToInt32(regiondrop.SelectedValue);
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==selectedValue
You could also do (but the previous solution is more readable)
var dq=(from dropdwn in ts.tblRes
where SqlFunctions.StringConvert((double)dropdwn.RegionID)==regiondrop.SelectedValue
There's a method in SqlFunctions to convert a numeric to a string, but... not a string to a numeric value.
I have got 2 asp pages. Firstly i get logged in through log in page and 2nd page is home page where i got few buttons of some tasks. Along with that i got user details which consists of FULLNAME,ADDRESS,CELL NUMBER,BLOOD GROUP and EMAILID, this should be displayed dynamically in their particular labels from DATABASE once the user logs in using his username and password.
I have written Query for this within the GetLoginDetails Stored Procedure. I have to display Employee Name,his Last Login Date,Time etc. once his log in and enters home page in the same way i should get user details.
ALTER PROCEDURE [dbo].[GetLastLogin]
#LoggedInUser nvarchar(50),
#FullName nvarchar(50),
#Address nvarchar(50),
#MobileNumber bigint,
#EmailID nvarchar(50),
#BloodGroup nvarchar(50),
#EmpName nvarchar(50)
As
Declare #LastLogin int
Set #LastLogin = (Select MAX(AccessID)from dbo.ACCESS_INFO where Flag = 1)
Select Access_Date, Access_Time from dbo.ACCESS_INFO where LoggedInUser = #LoggedInUser and AccessID = #LastLogin
Update dbo.EmployeeData
Set Empname = #EmpName
where FullName = #FullName and Address = #Address and MobileNumber = #MobileNumber and EmailID = #EmailID and BloodGroup = #BloodGroup ;
im getting error saying tht ("Procedure or function 'GetLastLogin' expects parameter '#FullName', which was not supplied.") please help me out
back end code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
try
{
MTMSDTO objc = new MTMSDTO();
LblLogdInUser.Text = Session["EmpName"].ToString();
LblUser.Text = Session["Username"].ToString();
objc.LoggedInUser = LblUser.Text;
DataSet laslogin = obj.GetLastLogin(objc);
DataView LasLogin = new DataView();
LasLogin.Table = laslogin.Tables[0];
GrdLasLogin.DataSource = LasLogin;
GrdLasLogin.DataBind();
if (!IsPostBack)
{
int lastlog = GrdLasLogin.Rows.Count;
if (lastlog == 0)
{
LblLastLoginD.Text = "This is your First Login";
DateTime today = System.DateTime.Now.Date;
LblToday.Text = today.ToString();
LblTime.Text = System.DateTime.Now.ToLongTimeString();
objc.LoggedInUser = LblLogdInUser.Text;
objc.AccessDate = Convert.ToDateTime(LblToday.Text);
objc.AccessTime = Convert.ToDateTime(LblTime.Text);
objc.AccessStatus = "New Login";
objc.AccessFlag = 1;
int accessinfo = obj.InsertAccessInfo(objc);
}
else
{
LblLastLoginD.Text = Convert.ToDateTime(GrdLasLogin.Rows[0].Cells[0].Text).ToString("dd/MMM/yyyy");
LblLastLoginT.Text = GrdLasLogin.Rows[0].Cells[1].Text;
DateTime today = System.DateTime.Now.Date;
LblToday.Text = today.ToString();
LblTime.Text = System.DateTime.Now.ToLongTimeString();
objc.LoggedInUser = LblLogdInUser.Text;
objc.AccessDate = Convert.ToDateTime(LblToday.Text);
objc.AccessTime = Convert.ToDateTime(LblTime.Text);
objc.AccessStatus = "New Login";
objc.AccessFlag = 1;
int accessinfo = obj.InsertAccessInfo(objc);
}
LblFname.Visible = true;
LblAdd.Visible = true;
LblMnum.Visible = true;
LblMailID.Visible = true;
LblBGroup.Visible = true;
}
}
catch (Exception ex)
{
Response.Redirect("ERROR.aspx");
Session.Abandon();
}
}
else
{
Response.Redirect("~/Login.aspx");
}
Response.CacheControl = "no-cache";
}
The error message makes it clear that you need to supply values for the parameter FullName. So, if you aren't already doing that, then go do that. The only complication here is null values; a string can be null, but to specify that in ADO.NET you need to pass DBNull.Value; if you use null the parameter is not included. This means you end up with code like:
cmd.Parameters.AddWithValue("FullName", (object)fullName ?? DBNull.Value);
Ugly, but it works.
Alternatively, many helper utilities will do this for you. So with "dapper":
var lastAccess = conn.Query<AccessInfo>("GetLastLogin",
new { LoggedInUser = cn, FullName = fullName, /* snipped */ },
commandType: CommandType.StoredProcesdure).FirstOrDefault();
The problem is not in your SQL. It's in your calling function in asp. You are not sending the fullname parameter to SQL server correctly. Check out this question for an example on how to send parameters.
Call a stored procedure with parameter in c#
I have a model-first EF model. I just imported the first stored procedure: cpas_POIDVendorProjectDate
I imported it as a function. It has three input parameters: #ProjectID(int), #VendorID(int), and #Workdate(datetime), and returns #POID(int).
Here's the SQL code:
CREATE PROCEDURE [dbo].[cpas_POIDVendorProjectDate]
#VendorID int,
#ProjectID int,
#WorkDate datetime,
#PO_ID int OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #RowCount int;
SELECT #PO_ID = ID FROM tblPO WHERE
VendorID = #VendorID
AND ExpirationDate >= #WorkDate
AND (ProjectID IS NULL OR ProjectID = #ProjectID)
AND CapitalExpense = (
SELECT CapitalExpense FROM tblProjects WHERE ID=#ProjectID)
AND GroupCode in (1,3,5);
SET #RowCount = ##RowCount;
IF (#RowCount != 1)
SET #PO_ID = -1*#RowCount;
END
I called it in my c# program as follows:
context.cpas_POIDVendorProjectDate(
currVendorID, currProjectID, currWorkDate, currPOID);
Intellisense says my use of "context" is wrong...It's a "variable", and I'm using it as a "method".
In addition, currPOID is rejected because it's looking for a system.data.objects.OjbectParameter, not an int. Intellisense is happy with the function name and other parameters (strangely...)
What am I doing wrong here?
You can always do this if nothing else works:
using(var context = new MyDataContext())
{
using(var cmd = context.Database.Connection.CreateCommand())
{
cmd.CommandText = "cpas_POIDVendorProjectDate";
cmd.CommandType = CommandType.StoredProcedure;
//if the stored proc accepts params, here is where you pass them in
cmd.Parameters.Add(new SqlParameter("VendorId", 10));
cmd.Parameters.Add(new SqlParameter("ProjectId", 12));
cmd.Parameters.Add(new SqlParameter("WorkDate", DateTimw.Now));
var poid = (int)cmd.ExecuteScalar();
}
}
If you would like an object orientated way, then Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....
using (testentities te = new testentities())
{
//-------------------------------------------------------------
// Simple stored proc
//-------------------------------------------------------------
var parms1 = new testone() { inparm = "abcd" };
var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
var r1 = results1.ToList<TestOneResultSet>();
}
... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...
[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
[TestMethod]
public void GetTenantForName_ReturnsOneRecord()
{
// ARRANGE
const int expectedCount = 1;
const string expectedName = "Me";
// Build the paraemeters object
var parameters = new GetTenantForTenantNameParameters
{
TenantName = expectedName
};
// get an instance of the stored procedure passing the parameters
var procedure = new GetTenantForTenantNameProcedure(parameters);
// Initialise the procedure name and schema from procedure attributes
procedure.InitializeFromAttributes();
// Add some tenants to context so we have something for the procedure to return!
AddTenentsToContext(Context);
// ACT
// Get the results by calling the stored procedure from the context extention method
var results = Context.ExecuteStoredProcedure(procedure);
// ASSERT
Assert.AreEqual(expectedCount, results.Count);
}
}
internal class GetTenantForTenantNameParameters
{
[Name("TenantName")]
[Size(100)]
[ParameterDbType(SqlDbType.VarChar)]
public string TenantName { get; set; }
}
[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
: StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
public GetTenantForTenantNameProcedure(
GetTenantForTenantNameParameters parameters)
: base(parameters)
{
}
}
If either of those two approaches are any good?