ASP.NET - Add from 2Registered table How ?
Asked By Rahul
03-Feb-12 06:39 AM

i have 2 register tables like member,agent, in member table have 2users like raj,ram in agent table have 2users like sam,shan,
i want to check and insert from that 2 tables. now i am going to give creditpoint to the exist 2tables user, i give creditpoint to the exist user means it will add in another points table but 2nd time i give the point means it will not taken it shows already point was given to this and display in gridview, but i add new user means it shows not having user like this, how it was ?
i have coding like this:
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd=new SqlCommand("select Count(*) from agentreg where userid='" +TextBox1.Text+ "' and username='"+TextBox2.Text+"'",con);
int i = (int)cmd.ExecuteScalar();
if (i != 0)
{
cmd =
new SqlCommand("select count (username) from creditadd where services ='" + DropDownList1.SelectedItem.Value + "' and username='" + TextBox2.Text + "' and userid='" + TextBox1.Text + "'", con);
int j = (int)cmd.ExecuteScalar();
if (j == 0)
{
cmd = new SqlCommand("insert into creditadd values (@userid,@username,@services,@credit)", con);
cmd.Parameters.AddWithValue(
"userid", TextBox1.Text);
cmd.Parameters.AddWithValue("username", TextBox2.Text);
cmd.Parameters.AddWithValue(
"services", DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue("credit", TextBox3.Text);
cmd.ExecuteNonQuery();
TextBox1.Text =
"";
TextBox2.Text = "";
TextBox3.Text =
"";
Response.Write("<script>alert('Successfull');</script>");
bindgrid();
dropbind();
}
else
{
Response.Write("<script>alert('Already Exist');</script>");
}
}
else
{
Response.Write("<script>alert('Not Registered');</script>");
}
cmd =
new SqlCommand("select Count(*) from memreg where userid='" + TextBox1.Text + "' and username='" + TextBox2.Text + "'", con);
int k = (int)cmd.ExecuteScalar();
if (k != 0)
{
cmd = new SqlCommand("select count (username) from creditadd where services ='" + DropDownList1.SelectedItem.Value + "' and username='" + TextBox2.Text + "' and userid='" + TextBox1.Text + "'", con);
int l = (int)cmd.ExecuteScalar();
if (l == 0)
{
cmd =
new SqlCommand("insert into creditadd values (@userid,@username,@services,@credit)", con);
cmd.Parameters.AddWithValue("userid", TextBox1.Text);
cmd.Parameters.AddWithValue(
"username", TextBox2.Text);
cmd.Parameters.AddWithValue("services", DropDownList1.SelectedItem.Value);
cmd.Parameters.AddWithValue(
"credit", TextBox3.Text);
cmd.ExecuteNonQuery();
TextBox1.Text = "";
TextBox2.Text =
"";
TextBox3.Text = "";
Response.Write(
"<script>alert('Successfull');</script>");
bindgrid();
dropbind();
}
else
{
Response.Write("<script>alert('Already Exist');</script>");
}
}
else
{
Response.Write("<script>alert('Not Registered');</script>");
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
[)ia6l0 iii replied to Rahul

Frankly speaking this is Bad Code.
Please use stored procedure to do your business logic. Don't traverse between webserver and the database for a logic like this.
I have few recommendations as well.
a) Use a Using statement on the objects like SQL Connection. That will take care of closing and disposing it.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
///your other code.
}
b) Do not use statements like "Select Count(*) from agentreg". Instead, use "Select Count(1) from AgentReg". That is a quicker way.
c) Do not create inline queries for your ExecuteScalar as well. Create SQLParameters and pass this information to a stored procedure.
SqlCommand command = new SqlCommand();
command.Connection = yourConnectionObject;
command.CommandText = "stored procedure name";
command.CommandType = CommandType.StoredProcedure;
//Adding parameter.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@userid";
parameter.SqlDbType = SqlDbType.Int;
parameter.Direction = ParameterDirection.Input;
parameter.Value = userid;
//Adding parameter to the command object.
command.Parameters.Add(parameter);
Please do all these changes. Let's first write manageable and readable code.
Hope this helps.

can browse the products but when I try to register a user I get the error System.InvalidCastException: Specified cast is not valid. on line 503 of the customerdb.cs / / Calculate so many times and with different data type and cases. your stack trace specifies that error is at line 503 of CustomersDB.cs. try debugging method AddCustomer Thanks , This is from name, email, password, etc). / / / / Other relevant sources: / / + <a href = "usp_CustomerDetail.htm" style = "color:green"> usp_CustomerDetail Stored Procedure< / a> / / / / * ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** public CustomerDetails GetCustomerDetails(String customerID) { / / Create Instance of Connection and Command Object SqlConnection myConnection a SPROC myCommand.CommandType = CommandType.StoredProcedure; / / Add Parameters to SPROC SqlParameter parameterCustomerID = new SqlParameter("@CustomerID", SqlDbType.Int, 4); parameterCustomerID.Value = Int32.Parse(customerID, CultureInfo.InvariantCulture); myCommand.Parameters.Add(parameterCustomerID); SqlParameter parameterFirstName = new SqlParameter("@FirstName", SqlDbType.NVarChar, 50); parameterFirstName.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterFirstName); SqlParameter parameterLastName = new SqlParameter("@LastName SqlDbType.NVarChar, 50); parameterLastName.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterLastName); SqlParameter parameterEmail = new SqlParameter("@Email
Stored Procedure Using in C# Hi. I have a question about inserting into multiple tables. I have I want to insert a new row into two of these tables. I use a stored procedure for this, but it gives me several errors in C# when I use it ! Tables as a result I have to add a row to "Users_Credits" table. Here is my stored procedure: CREATE PROCEDURE [dbo].[spAddTransaction] @CreditId int output, @PreviousCredit int, @DepositAmount int, @Sum int, @UserId int AS INSERT Data.CommandType.StoredProcedure; oCommand.CommandText = "SP_InsertNewTrans" ; oCommand.Parameters.Clear(); / / oCommand.Parameters.Add("@CreditId", System.Data.SqlDbType.Int); / / oCommand.Parameters["@CreditId"].Direction = System.Data.ParameterDirection.Output; oCommand.Parameters.Add( "@PreviousCredit" , System.Data
article - http: / / support.microsoft.com / kb / 326502 SQL Server Script To Create Images Table And Stored Procedures if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Images]') and OBJECTPROPERTY dbo.sysobjects where id = object_id(N'[dbo].[GetImage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[GetImage] GO if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SaveImage]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[SaveImage] GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS OFF GO CREATE PROCEDURE dbo.GetImage ( @ImageID int ) as select ImageFile from Images where ImageID = @ImageID GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS OFF GO CREATE PROCEDURE dbo.SaveImage ( @ImageID int = 0, @ImageFile image, @NewID int output ) AS declare @rc int select rc = 0 if (@ImageID = 0) BEGIN insert Images (ImageFile) values (@ImageFile) select @NewID = @@identity if (@@Error <> 0) select @rc = 1 Goto OnExit END Update Images Set ImageFile = @ImageFile where ImageID = @ImageID if (@@Error <> 0) select @rc = 1 Goto OnExit select @NewID = @ImageID OnExit: return @rc GO SET QUOTED_IDENTIFIER oTable); oConn.Close(); } catch (Exception e) { throw new Exception(e.Message);} finally { if (oConn.State = = ConnectionState.Open) { oConn.Close(); } } return oTable; } public int SaveImage(string sConnectionString, int nImageID, byte[] oImage) { string
ds.Tables[0]); dgResults.DataSource = source ; dgResults.DataBind(); dbConn.Close(); Here is the SP: CREATE PROCEDURE cdOrders ( @cdClientID int, @itemIDList Varchar( 500 ), @cdClientName Varchar( 100 ), @cdItemName Varchar( 100 ), @orderDate datetime, @shipDate the way you are doing You should declare @cdSerialNumID as an output parameter as . . . . CREATE PROCEDURE cdOrders ( @cdClientID int, @itemIDList Varchar( 500 ), @cdClientName Varchar( 100 ), @cdItemName Varchar( 100 ), @orderDate datetime, @shipDate Prathmesh What you suggested is what I had origionally tried but I get the following error which was what led me to declare it the way I did, which does not of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: The SqlParameterCollection only accepts non-null SqlParameter type objects, not String objects. Source Error: Line 109: cmdSNItems.Parameters.Add("@orderDate", txtOrderDate.Text); Line 110: cmdSNItems.Parameters.Add("@shipDate", txtShipDate would explain why nothing is returned - - but why? dbConn.Open(); cmdSNItems.ExecuteScalar(); if (dbConn.State = = ConnectionState.Closed) Response.Redirect("default.aspx"); You need to specify the datatype and the direction of the parameter cmdSNItems.Parameters.Add("@cdSerialNumID ", SqlDbType.Int) cmdSNItems.Parameters["@cdSerialNumID"].Direction = ParameterDirection.Output; and after executing the stored procedure usingNonQuery get the return vakue as. int iCount
ADODB.Connection") oCon.CursorLocation = adUseClient oCon.open "connection string" oCon.Execute "my sql string or stored procedure code" If oCon.STATE = adStateOpen Then oCon.Close Set oCon = Nothing ADO.NET - Execute SQL SqlCommand oCmd = new SqlCommand("update mytable set mycol = 'hello' where blah = 'stuff'", oConn); / / Or a stored procedure. . . / / SqlCommand oCmd = new SqlCommand("exec myprocedurename 'hello'", oConn); nRowsAffected = oCmd.ExecuteNonQuery(); } catch (Exception err) { throw err; } finally { if (oConn.State = = ConnectionState.Open) { oConn.Close(); } } ADO - Disconnected Recordset From SQL Query Set oCon = Server.CreateObject("ADODB.Connection my table", oConn); oDA.Fill(oTable); oConn.Close(); } catch (Exception e) { } finally{ if (oConn.State = = ConnectionState.Open) { oConn.Close(); } } / / To Iterate Through Rows foreach(DataRow oRow in oTable.Rows) { Response.Write(oRow["username"].ToString()); } ADO - Disconnected Recordset From Stored Procedure Set oCon = Server.CreateObject("ADODB.Connection") Set oRec = Server.CreateObject("ADODB.Recordset") oCon.CursorLocation = adUseClient