DataGrid view in asp.net is not displaying data - asp.net

I want to dispaly column in datagrid view using custom query statement
but i want to send value to parametrized data in query
how can i do this ?
my code is below
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'cus0010' and a.account_number = 'acc0010'
this above code working properly in sql server 2005
but the code below which is modified as per asp.net page for grid view is not showing
any result
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'Label1.Text' and a.account_number = 'Label2.Text'
the above is placed in my custom sql query section it
is triggered by button click in my asp page or any other
idea to display it will be welcomed

Use:
string.Format("c.customer_id = '{0}' and a.account_number = '{1}'", Label1.Text, Label2.Text);
Consider this query:
string query = "insert into TestTable (Column1, Column2) values (#p1, #p2)";
p1 & p2 are parameters, in order to set the value for the parameters you need to use:
queryParameters[0] = new SqlCeParameter("p1", SqlDbType.NVarChar);
queryParameters[0].Value = Label1.Text;
queryParameters[1] = new SqlCeParameter("p2", SqlDbType.NVarChar);
queryParameters[1].Value = Label2.Text;
SqlCeCommand command = new SqlCeCommand(query);
command.Parameters.AddRange(queryParameters);
When the wizard is generating the query you need to use place holders/parameters for customer_ID and account_number and set their values by using parameters.
Edit:
In order to make the wizard create a parameter to use in the query, add a ? in the filter column in the query builder wizard.

Well, I may misunderstand, but...you are not actually sending the string 'Label1.Text' I guess? You should send the value of the textbox, something like this (if you are building the SQL as a string?):
...[SQL]... + "c.customer_id = '"+ Label1.Text + "'" ...[rest of the SQL]

Related

Stored Procedure for inserting text field values that is created dynamically to the same id using asp.net C#

Im new to ASP.net webforms.Im having a event page,in which i have a field to add sales channel heads mail id.when i click on the plus button i will be able to add more than one sales channels head.
For inserting the form values into the database im using Stored procedure.and its inserting the records with one sales channel head email id.
I want to know how i can write a stored procedure for inserting dynamic textbox values into sql server for the same record(That is the id and event name should be same).
This is my stored procedure
CREATE PROCEDURE SPInsertEvent
#eventName varchar(200),
#eventDate date,
#costPerHead varchar(200),
#totalCost varchar(200),
#salesChannelHeads varchar(200),
#salesManagers varchar(200),
#eventCreationTime datetime
AS
BEGIN
SET NOCOUNT ON
-- Insert statements for procedure here
INSERT INTO dbo.hp_event
(event_name, event_date, cost_per_head, total_cost, sales_channel_head, sales_manager, event_creation_time)
VALUES
(#eventName, #eventDate, #costPerHead, #totalCost, #salesChannelHeads, #salesManagers, #eventCreationTime)
END
This is my ASP.net function
SqlCommand cmd = new SqlCommand("SPInsertEvent", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("EventName", txtEventName.Text);
cmd.Parameters.AddWithValue("EventDate", Convert.ToDateTime(txtEventDate.Text));
cmd.Parameters.AddWithValue("CostPerHead", txtTotCostPerHead.Text);
cmd.Parameters.AddWithValue("TotalCost", txtTotalCostEvent.Text);
cmd.Parameters.AddWithValue("SalesChannelHead", txtSalesChannelHead.Text);
cmd.Parameters.AddWithValue("SalesManager", txtSalesManagers.Text);
cmd.Parameters.AddWithValue("EventCreationTime", DateTime.Now);
conn.Open();
int k = cmd.ExecuteNonQuery();
if (k != 0)
{
string message = "Event added successfully.";
string script = "window.onload = function(){ alert('";
script += message;
script += "')};";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
conn.Close();
Instead of storing all the list of email ids for the given event in one table, I would suggest you to store them in separate table and you can reference them from the hp_event table whenever you need. So your database design should be some thing like below where eventid of hp_eventSalesManagers references eventId of hp_event -
To make this design work you can make use of Table Valued Parameters in ADO.NET and follow the below steps:
Create a User Defined Type -
CREATE TYPE [dbo].[ChannelHeads] As Table
(
EmailIds VARCHAR(50)
)
Whenever you click button populate a new Data Table(I am using Session to keep track
of the previous data), below is the sample code:
protected void btnAdd_Click(object sender, EventArgs e)
{
if (Session["DataTable"] == null)
{
dataTable = new DataTable();
dataTable.Columns.Add("EmailIds", typeof(string));
Session.Add("DataTable", dataTable);
}
else
{
//If yes then get it from current session
dataTable = (DataTable)Session["DataTable"];
}
DataRow dt_row;
dt_row = dataTable.NewRow();
dt_row["EmailIds"] = name.Text;
dataTable.Rows.Add(dt_row);
}
When submitting to data base add the below parameter(See the way I am passing the data table to DB):
SqlParameter parameterSalesChannelHeads = new SqlParameter();
parameterSalesChannelHeads.ParameterName = "#salesChannelHeads";
parameterSalesChannelHeads.SqlDbType = System.Data.SqlDbType.Structured;
parameterSalesChannelHeads.Value = (DataTable)Session["DataTable"];
parameterSalesChannelHeads.TypeName = "dbo.ChannelHeads";
cmd.Parameters.Add(parameterSalesChannelHeads);
Change all your parameters in above format just to make sure you are using
Parameters.Add instead of Parameters.AddWithValue as mentioned here
Finally change the procedure as below to populate the tables, below is one of the way,
you can enable error handling and improve the code:
ALTER PROCEDURE SPInsertEvent
#eventName varchar(200),
#eventDate datetime,
#costPerHead varchar(200),
#totalCost varchar(200),
#salesChannelHeads As [dbo].[ChannelHeads] Readonly,
#salesManagers varchar(200),
#eventCreationTime datetime
AS
BEGIN
SET NOCOUNT ON
DECLARE #eventID INT
-- Insert statements for procedure here
INSERT INTO dbo.hp_event
(event_name, eventDate, costPerHead, totalCost, eventCreationTime,
salesManagers)
VALUES
(#eventName, #eventDate, #costPerHead, #totalCost,#eventCreationTime,
#salesManagers)
SET #eventID = SCOPE_IDENTITY()
INSERT INTO dbo.hp_eventSalesManagers
(eventid,event_name,salesChannelHeads)
SELECT #eventID, #eventName, EmailIds
FROM
#salesChannelHeads
END
Finally change the data types of the fields accordingly as mentioned in the comment section for better clarity and usages.
You said in the comments "What i need is a stored procedure for inserting saleschannel heads email id(txtSalesChannelHead,txtSalesChannelHead1,txtSalesChannelHead2) into the sql server table with same id,that is there will be duplicate rows in the table". Handling a dynamic number of inputs like that is not best done in a stored procedure, from what i can see of your scenario. The easier way is to run the insert procedure from your .NET code once for each textbox. Now I don't know how your textboxes are being added, so I can't tell you how to get the set of textbox values, but once you have it, a simple foreach loop will let you run the stored procedure once for each of them.

how to copy data to data table in linq step by step process in linq

I am fresher in linq,So please give me the link or write step by step procedure to fill data table in linq.
here is the code
var Sql = from t1 in pitbull.ACC_APP1_QuickViews.AsEnumerable()
join t2 in pitbull.OCC_VehicleGroups.AsEnumerable()
on t1.VehicleId equals t2.VehicleID
select new
{
t1.Lat,
t1.Lon,
t1.Timestamp_GPS,
t1.Speed,
t1.Location,
t1.Status,
t1.VehicleRegNo,
t1.VehicleId,
t2.VGID,
t2.VGName
};
DataTable dt = new DataTable();enter code here
dt=Sql.copytodatatable();
//copy to datatable not support.Improve question Permalink
It is because you are creating a anonymous type using select new{ } to hold the Field objects. Try this:
var Sql = from t1 in pitbull.ACC_APP1_QuickViews.AsEnumerable()
join t2 in pitbull.OCC_VehicleGroups.AsEnumerable()
on t1.VehicleId equals t2.VehicleID
select t2;
DataTable dt = Sql.copytodatatable();

how to update a column( in SQL) by adding a specific amount to the old one?

thats the code...
SQL = string.Format("Insert into Orders (AID,ODate) Values({0},'{1}')", AID, odate);
Dbase.ChangeTable(SQL, "Database1.mdb");
SQL = "Select MAX(OID) as MAXOID from Orders";
dt = Dbase.SelectFromTable(SQL, "Database1.mdb");
OID = dt.Rows[0][0].ToString();
string PID = Session["PID"].ToString();
SQL = string.Format("Insert into ListedProducts (OID,PID,PCat,cnt) Values({0},{1},'{2}',{3})", OID, PID, "B", cnt);
Dbase.ChangeTable(SQL, "Database1.mdb");
Label6.Text = "Your Product has been added to your basket , go to your basket to commit your order.";
// HEREEEEEEE///
SQL = String.Format("Update [Orders] SET [price]=[price]+{0} Where [OID]={1}", int.Parse(cnt) * pr, OID);
//SQL = "UPDATE [Orders] SET [price]=" + int.Parse(cnt) * pr + " WHERE OID=" + OID;
////////////////
Dbase.ChangeTable(SQL, "Database1.mdb");
so it should work and it doesnt show me an error but it doesnt add anything to the database but if i wont be adding it would update.
my database consists of OID,ODate,price,AID..
Run the SQL Commands manually and ensure your logic is correct... it's possible that your UPDATE is running but not doing anything since your WHERE isn't finding the OID you're passing in.

Firebird insert...returning asp.net

I'm using Firebird 2.5 and asp.net (4.5).
I'm trying to find out how to use insert ... returning, or some equivalent.
Using fbDataReader, it executes the insert OK, but I can't find anyway of accessing a returned value. Using fbDataReader.GetName(0) seems to work ok, returning the variable name in the "returning" clause. This even applies to a max() in a subselect:
..... returning (select max(userid) as newid from users)
returns the text "newid".
I can't find where, or whether, the value is available.
Using a fbDataAdaptor to fill a DataTable, the insert works OK, but data table seems empty.
Does anyone know whether this is possible, and if so, how it's done?
Thanks
EDIT
Code supplied :
strConn = ....
dbConn = New FirebirdSql.Data.FirebirdClient.FbConnection(strConn)
dbConn.Open()
MySQL = "insert into users (Firstname, Lastname) VALUES (#fname,#lname) returning userid"
FbC = New FirebirdSql.Data.FirebirdClient.FbCommand(MySQL, dbConn)
FbC.Parameters.Add("fname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Pete"
FbC.Parameters.Add("lname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Davis"
FbDataReader = FbC.ExecuteReader()
FbDataReader.Read()
TextBox1.Text = FbDataReader.GetName(0)
'TextBox1.Text = str(FbDataReader.GetInt64())
'TextBox1.Text = FbDataReader.GetString(0)
TextBox1.Text = FbDataReader.GetValue(0)
According to this thread INSERT ... RETURNING ... behaves like output parameters for the Firebird .NET provider. So you will need to add an output parameter.
So something like the code below should work:
FbParameter outParam = new FbParam("userid", FbDbType.Integer)
{
Direction = ParameterDirection.Output
};
FbC.Parameters.Add(outParam);
FbC.ExecuteNonQuery();
int? userId = outParam.Value as int?;

Selected value from dropdownlist has to be tablename from linq query

I have a problem with my linq query. I want a search field (textbox) with a dropdownlist next to it. When i set the dropdownlist on "ProductID" he has to search only in the table "ProductID", And when i put it on "Productinformation", he has to search in the table "productinformation", i hope somebody understand this?
So what i want is the following query:
var textboxvalue = TextBox1.Text;
var dropdownsearch = DropDownList1.SelectedValue;
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
where (m. {{{Here i want the dropdownsearch}}} .ToString().Contains(textboxvalue) ||
mm. {{{Here i want the dropdownsearch}}} .ToString().Contains(textboxvalue))
select new
{
mm.ProductID,
mm.filename,
mm.filetype,
mm.filesize
};
So, how can i get the selected value from the dropdownlist, as a table in the query? Normally you would put m.ProductID into the query, but i want the Selected value in it, something like m.(Dropdownlist1.Selectedvalue)... or m.dropdownsearch..
Is that possible? And how?
Thanks :)
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
select new { m, mm };
var filtered = Metadata.Where("m." + dropdownsearch + " like '#0'", textboxvalue);
var filtered = Metadata.Where("mm." + dropdownsearch + " like '#0'", textboxvalue);
var result = filtered.Select(f => new
{
f.mm.ProductID,
f.mm.filename,
f.mm.filetype,
f.mm.filesize
};

Resources