Updating data from GridView - asp.net

I have a Gridview where I join two tables, bringing in the data to be displayed
table 1 sid, schedule, stime, splace, stourid
table 2 tourid, tourname
Basically they are joined stourid to tourid. That is so I can show the tourname in the grid.
Now I want to edit this GridView, what do I need to do, for instance, if the user edits the tourname, that it'll be saved to the database? I assume an Update statement is need, but how does it link to the GridView?
Whats the best and neatest method?
Regards,

Create Store Procedure to Update both tables and call it in your Update Code...
Create Proc UpdateData
#sid int,
#schedule,
#stime,
#splace,
#tourname
as
Begin
declare #tourid int,
select distinct #tourid=tourid from table1 where sid=#sid
begin try
// update tabel1
update tabel2 set tourname=#tourname where tourid =#tourid
end Try
begin Catch
end Catch
End

Using LinqToSQL you can do something like (if there is a FK relation between the tables)
DatabaseDataContext data = new DatabaseDataContext();
Table1 row = data.Table1s.Where(t =>t.ID == selectedID);
row.Table2.tourname = newName;
data.SubmitChanges();
You would then want to rebind the grid to show the new data.

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.

PLSQL how to store a result of a select statement

I need to delete data from many tables based on one parameter
The problem is that two tables are related to each other so in order to delete data properly i need to store id's somewhere.
-- i would like to store temp data
-- this one is only for convienience to avoid repeating same select many times
create table ztTaryfa as select zt_taryfa from tw_zbiory_taryfy
where 1=2;
-- this one is mandatory but I dont know how to make it work
Create table wnioskiId as select poli_wnio_id_wniosku from polisy
where 1=2;
Begin
-- fill temp tables
insert into ztTaryfa (
select zt_taryfa from tw_zbiory_taryfy
where zt_zbior = :zbiorId);
insert into wnioskiId (
select poli_wnio_id_wniosku from polisy
where poli_taryfa_id in ztTaryfa);
- regular deletion
delete from POLISY_OT where ot_poli_id in (
select poli_id from polisy
where poli_taryfa_id in ztTaryfa);
commit;
delete from DANE_RAPORTOWE where DR_RPU_ID in (
select RPU_ID from ROZLICZ_PLIK_UBEZP where RPU_ROZLICZ_PLIK_ID in (
select RP_ID from ROZLICZ_PLIK
where RP_ZBIOR_ID = :zbiorId ));
commit;
-- and here we go I need to delete data from POLISY first
delete from POLISY where poli_taryfa_id in ztTaryfa;
commit;
-- but by doing it I lose ids which i need here,
-- so I have to store them somehow and use them here.
delete from WNIOSKI where wnio_id in wnioskiId;
commit;
End;
-- and now lets get rid off temp tables
drop table ztTaryfa;
commit;
drop table wnioskiId;
commit;
To sum up i just need to know how to store somewhere between Begin and End a result of a select query which I can later use in delete statement.
Sounds but I tried so many different methods and all seems to not work.
What u see above is just a 1/3 of the script so I rly would like to make it all simple to use with one parameter.
Thanks you in advance.
You can use global types as simple as this:
create or replace type myrec is object (myid number);
create or replace type mytemp_collection is table of myrec;
declare
v_temp_collection mytemp_collection;
begin
v_temp_collection := mytemp_collection();
select myrec (t.field_type_id ) bulk collect into v_temp_collection from fs_field_types t
where mod(t.field_type_id+1,3)=0; -- for example
FOR i IN 1 .. v_temp_collection.count LOOP
DBMS_OUTPUT.put_line(v_temp_collection(i).myid);
End loop;
delete fs_field_types_back t where t.field_type_id in (select myid from table(v_temp_collection));
end;
Change select and where clause according to your business.

retrieve checkboxlist selection from database

I have a checkboxlist which when submitted stores the selections in a table with the userid.The table is shown below :
Create table tblInterestByUserId
(
Id int primary key identity,
UserId varchar(10),
SubInterestId int,
SubInterest varchar(20),
InterestId int
)
Now i want to retrieve the selection on another checkboxlist on another page depending upon SubInterestId.I want to do something like this on the new page :
1.Going through all inserted SubInterest rows in tblInterestByUserId for the selected UserId.
2.Populating the checkboxlist according to the SubIinterest already present in tblInterestByUserId for that UserId
Please help me with a code-behind for the same on Page_Load.
Maybe a procedure to get the data you want....
CREATE PROCEDURE get_selections
#SubInterestId INT
AS
BEGIN
SET NOCOUNT ON;
SELECT SubInterest FROM tblInterestByUserId
WHERE SubInterestId = #SubInterestId
END
Call this procedure from the application code
My sugestion is tu use an enum with Flags in C# that maps with the subinterestID so then you can select the stored Ids and assign them to the enum.
see this:
http://forums.asp.net/t/1646982.aspx?enums+and+checkboxlist

Stored Procedure value to asp.net page under text box

I have a store procedure which show single row value like
(x.CLTotalAc, x.CLTotalAmt,x.CLAc, x.CLAmt,x.CL,
y.GB_CLTotalAc,y.GB_CLTotalAmt, y.GB_CLAc, y.GB_CLAmt, y.GB_CL).
I want these value to my asp.net C# page under text box (txtCLTotalAmt,
txtCL, txtGB_CLTotalAmt, txtGB_CL)
Store Procedure
ALTER proc [dbo].[Cr_CL_Report]
#ProductName text,
#BranchName text
as
begin
Select x.CLTotalAc,x.CLTotalAmt,x.CLAc, x.CLAmt,x.CL,
y.GB_CLTotalAc,y.GB_CLTotalAmt, y.GB_CLAc, y.GB_CLAmt, y.GB_CL
from
(
SELECT COUNT(dbo.DDBranchName.BCode) AS BrCode,
dbo.TblTotalCL.CLProductName AS ProductName,
SUM(dbo.TblTotalCL.CLTotalAc) AS CLTotalAc,
SUM(dbo.TblTotalCL.CLTotalAmt) AS CLTotalAmt,
SUM(dbo.TblTotalCL.CLAc) AS CLAc, SUM(dbo.TblTotalCL.CLAmt) AS CLAmt,
SUM(dbo.TblTotalCL.CLAmt)/SUM(dbo.TblTotalCL.CLTotalAmt) * 100 AS CL
FROM dbo.DDBranchName INNER JOIN
dbo.TblTotalCL ON dbo.DDBranchName.BCode = dbo.TblTotalCL.CLbrCode
WHERE (dbo.TblTotalCL.CLAsOnDate IN
(SELECT MAX(CLAsOnDate) AS Expr1 FROM dbo.TblTotalCL AS TblTotalCL_1))
AND (dbo.TblTotalCL.CLProductName LIKE #ProductName)
AND (dbo.DDBranchName.BCode LIKE #BranchName)
GROUP BY dbo.TblTotalCL.CLProductName
) x
inner join
(
SELECT COUNT(dbo.DDBranchName.BCode) AS GB_BrCode,
dbo.TblTotalCL.CLProductName AS GB_ProductName,
SUM(dbo.TblTotalCL.CLTotalAc) AS GB_CLTotalAc,
SUM(dbo.TblTotalCL.CLTotalAmt) AS GB_CLTotalAmt,
SUM(dbo.TblTotalCL.CLAc) AS GB_CLAc,
SUM(dbo.TblTotalCL.CLAmt) AS GB_CLAmt,
(SUM(dbo.TblTotalCL.CLAmt) / SUM(dbo.TblTotalCL.CLTotalAmt))*100 AS GB_CL
FROM dbo.DDBranchName INNER JOIN
dbo.TblTotalCL ON dbo.DDBranchName.BCode = dbo.TblTotalCL.CLbrCode
WHERE (dbo.TblTotalCL.CLAsOnDate IN
(SELECT MAX(CLAsOnDate) AS Expr1 FROM dbo.TblTotalCL AS TblTotalCL_1))
AND (dbo.TblTotalCL.CLProductName LIKE #ProductName)
GROUP BY dbo.TblTotalCL.CLProductName
) y on
x.ProductName = y.GB_ProductName
end
Blockquote
how can I solve this?
Getting return value from stored procedure in C#
In the link you can see how to get the values form a stored procedure. Then assign the value to the text box
Start by reading up on Ado.net. Use for instance the example here,under adonet data provider examples/sqlclient. When you have this working you have retrieved the data from the database. (imho avoid table adapters, entity framework and linqtosql if you want to grok it. instead go with manually writing for SqlCommand. or dapper to ease some of the burden.)
Now you have to get it to the web page. First decide on Webforms or Aspnetmvc. Then googlewithbing what the syntax is like.
Wash.
Rinse.
Repeat.
HTH

Update table using cursor but also update records in another table

I'm updating the IDs with new IDs, but I need to retain the same ID for the master record in table A and its dependants in table B.
The chunk bracketed by comments is the part I can't figure out. I need to update all the records in table B that share the same ID with the current record I'm looking at for table A.
DECLARE CURSOR_A CURSOR FOR
SELECT * FROM TABLE_A
FOR UPDATE
OPEN CURSOR_A
FETCH NEXT FROM CURSOR_A
WHILE ##FETCH_STATUS = 0
BEGIN
BEGIN TRANSACTION
UPDATE KEYMASTERTABLE
SET RUNNING_NUMBER=RUNNING_NUMBER+1
WHERE TRANSACTION_TYPE='TABLE_A_NEXT_ID'
-- FOLLOWING CHUNK IS WRONG!!!
UPDATE TABLE_B
SET TABLE_B_ID=(SELECT RUNNING_NUMBER
FROM KEYMASTERTABLE WHERE TRANSACTION_TYPE='TABLE_A_NEXT_ID')
WHERE TABLE_B_ID = (SELECT TABLE_A_ID
FROM CURRENT OF CURSOR A)
-- END OF BAD CHUNK
UPDATE TABLE_A
SET TABLE_A_ID=(SELECT RUNNING_NUMBER
FROM KEYMASTERTABLE WHERE TRANSACTION_TYPE='TABLE_A_NEXT_ID')
WHERE CURRENT OF CURSOR_A
COMMIT
FETCH NEXT FROM CURSOR_A
END
CLOSE CURSOR_A
DEALLOCATE CURSOR_A
GO
Based on the assumption that this process of incrementing current data by +1 doesn't cause issues in the data itself, I would create a translation table.
Column1 would be the old ID, Column2 would be the new ID.
Both tables would be run through the same update then.
This also gives you auditing on the process, in case something goes wrong.
Something like
Update table TargetA a
set a.id =(select t.column2 from tranlation_table t where t.column1 = a.id);
Update table TargetB b
set b.id =(select t.column2 from tranlation_table t where t.column1 = b.id)

Resources