Error inserting a field in sql

R

Ricardo Luceac

HI...

I have a web page that pass aa context to another..
The second page receives the context and need to put the value of the
context into a sql table..

The value is passing ok, 'cause i have a label that print the value, and
it's alright...

I pass the context value to a variable and try to imput it on the table
but the field always receive a 0 value...

heres my code:

int empresa= new int();

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
empresa=Convert.ToInt32(Context.Items["id_emp"].ToString());

Label7.Text=empresa.ToString();

}

// Here the label display the correct value of the "id_emp"


SqlConnection cnn = new
SqlConnection("server=(local);database=varired;trusted_connection=true")
;
SqlCommand cmm = new SqlCommand("Insert into contatos
(id_cliente,contato,depto,ddd,fone,ramal,email) values
(@a,@b,@c,@d,@e,@f,@g)",cnn);
cmm.Parameters.Add("@a",SqlDbType.Int).Value=empresa;

//But here it insert the number 0 on the table...


How can this happen???



[]s...
 
M

Martin Dechev

Hi,

Since you did not post the complete code of the page, I can only guess. My
guess is that you are inserting into the database on some button click
event, which happens when Page.IspostBack is true, so the code that sets the
field "empresa" is not executed and "empresa" is initialized to 0 (this is
what happens when you call the parameterless constructor of System.Int32).

What you can do, if this is the case, is to hold this value in the viewstate
like this:

public int Empresa
{
get
{
object result = ViewSate["empresa"];
if(result == null)
return 0;
return (int)result;
}
set{ViewState["empresa"] = value;}
}

Just set the property once when IsPostBack is false.

Hope this helps
Martin Dechev
ASP.NET MVP
 
R

Ricardo Luceac

Thanks... I didn't know that the value of the variable disapear with a
postback...
 
G

Guest

Yes it does. The web is a little different in that it doesn't keep track of
state variables on post back. Since, on each post back a new class for your
aspx page is generated. So, you have to use either viewstate, session
variables, application variables or some other persistance method to store
your temporary data.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,243
Members
46,835
Latest member
lila30

Latest Threads

Top