The query executes fine but the problem is that when this query executes And it doesn't update the percentage...












0















protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
int ID = (Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text));
string FirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string LastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string EmailID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string MobileNumber = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox5")).Text;
string Class = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox6")).Text;
string Stream = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox7")).Text;
string query = "UPDATE REIGISTRATION SET FirstName='" + FirstName + "', LastName='" + LastName + "', EmailID='" + EmailID + "', MobileNumber='" + MobileNumber + "', Class='" + Class + "', Stream='" + Stream + "' WHERE ID='" + ID + "'";
string cs = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
grid_binding();
}









share|improve this question

























  • Please format your query using the ` { } `

    – Squirrel
    Nov 24 '18 at 4:30











  • Your SQL in subject to an injection attack, use parameters instead

    – Mark Schultheiss
    Nov 24 '18 at 5:21











  • Please revise your question to include the field that you indicate is the issue, as it stands we cannot assist you given that missing key part.

    – Mark Schultheiss
    Nov 24 '18 at 5:27











  • The query is not working -- you need to capture the error returned to find the problem. It is probably a data type problem but we can't tell that without the data definitions.

    – Hogan
    Nov 24 '18 at 5:33











  • for example this code "' WHERE ID='" + ID + "'"; implies that IDs are strings. This would not be a common design.

    – Hogan
    Nov 24 '18 at 5:34


















0















protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
int ID = (Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text));
string FirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string LastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string EmailID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string MobileNumber = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox5")).Text;
string Class = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox6")).Text;
string Stream = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox7")).Text;
string query = "UPDATE REIGISTRATION SET FirstName='" + FirstName + "', LastName='" + LastName + "', EmailID='" + EmailID + "', MobileNumber='" + MobileNumber + "', Class='" + Class + "', Stream='" + Stream + "' WHERE ID='" + ID + "'";
string cs = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
grid_binding();
}









share|improve this question

























  • Please format your query using the ` { } `

    – Squirrel
    Nov 24 '18 at 4:30











  • Your SQL in subject to an injection attack, use parameters instead

    – Mark Schultheiss
    Nov 24 '18 at 5:21











  • Please revise your question to include the field that you indicate is the issue, as it stands we cannot assist you given that missing key part.

    – Mark Schultheiss
    Nov 24 '18 at 5:27











  • The query is not working -- you need to capture the error returned to find the problem. It is probably a data type problem but we can't tell that without the data definitions.

    – Hogan
    Nov 24 '18 at 5:33











  • for example this code "' WHERE ID='" + ID + "'"; implies that IDs are strings. This would not be a common design.

    – Hogan
    Nov 24 '18 at 5:34
















0












0








0








protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
int ID = (Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text));
string FirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string LastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string EmailID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string MobileNumber = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox5")).Text;
string Class = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox6")).Text;
string Stream = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox7")).Text;
string query = "UPDATE REIGISTRATION SET FirstName='" + FirstName + "', LastName='" + LastName + "', EmailID='" + EmailID + "', MobileNumber='" + MobileNumber + "', Class='" + Class + "', Stream='" + Stream + "' WHERE ID='" + ID + "'";
string cs = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
grid_binding();
}









share|improve this question
















protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
int ID = (Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text));
string FirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string LastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string EmailID = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string MobileNumber = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox5")).Text;
string Class = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox6")).Text;
string Stream = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox7")).Text;
string query = "UPDATE REIGISTRATION SET FirstName='" + FirstName + "', LastName='" + LastName + "', EmailID='" + EmailID + "', MobileNumber='" + MobileNumber + "', Class='" + Class + "', Stream='" + Stream + "' WHERE ID='" + ID + "'";
string cs = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
grid_binding();
}






c# asp.net sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 5:06









Rajesh Pandya

1,3112819




1,3112819










asked Nov 24 '18 at 4:22









Sandesh DubeySandesh Dubey

1




1













  • Please format your query using the ` { } `

    – Squirrel
    Nov 24 '18 at 4:30











  • Your SQL in subject to an injection attack, use parameters instead

    – Mark Schultheiss
    Nov 24 '18 at 5:21











  • Please revise your question to include the field that you indicate is the issue, as it stands we cannot assist you given that missing key part.

    – Mark Schultheiss
    Nov 24 '18 at 5:27











  • The query is not working -- you need to capture the error returned to find the problem. It is probably a data type problem but we can't tell that without the data definitions.

    – Hogan
    Nov 24 '18 at 5:33











  • for example this code "' WHERE ID='" + ID + "'"; implies that IDs are strings. This would not be a common design.

    – Hogan
    Nov 24 '18 at 5:34





















  • Please format your query using the ` { } `

    – Squirrel
    Nov 24 '18 at 4:30











  • Your SQL in subject to an injection attack, use parameters instead

    – Mark Schultheiss
    Nov 24 '18 at 5:21











  • Please revise your question to include the field that you indicate is the issue, as it stands we cannot assist you given that missing key part.

    – Mark Schultheiss
    Nov 24 '18 at 5:27











  • The query is not working -- you need to capture the error returned to find the problem. It is probably a data type problem but we can't tell that without the data definitions.

    – Hogan
    Nov 24 '18 at 5:33











  • for example this code "' WHERE ID='" + ID + "'"; implies that IDs are strings. This would not be a common design.

    – Hogan
    Nov 24 '18 at 5:34



















Please format your query using the ` { } `

– Squirrel
Nov 24 '18 at 4:30





Please format your query using the ` { } `

– Squirrel
Nov 24 '18 at 4:30













Your SQL in subject to an injection attack, use parameters instead

– Mark Schultheiss
Nov 24 '18 at 5:21





Your SQL in subject to an injection attack, use parameters instead

– Mark Schultheiss
Nov 24 '18 at 5:21













Please revise your question to include the field that you indicate is the issue, as it stands we cannot assist you given that missing key part.

– Mark Schultheiss
Nov 24 '18 at 5:27





Please revise your question to include the field that you indicate is the issue, as it stands we cannot assist you given that missing key part.

– Mark Schultheiss
Nov 24 '18 at 5:27













The query is not working -- you need to capture the error returned to find the problem. It is probably a data type problem but we can't tell that without the data definitions.

– Hogan
Nov 24 '18 at 5:33





The query is not working -- you need to capture the error returned to find the problem. It is probably a data type problem but we can't tell that without the data definitions.

– Hogan
Nov 24 '18 at 5:33













for example this code "' WHERE ID='" + ID + "'"; implies that IDs are strings. This would not be a common design.

– Hogan
Nov 24 '18 at 5:34







for example this code "' WHERE ID='" + ID + "'"; implies that IDs are strings. This would not be a common design.

– Hogan
Nov 24 '18 at 5:34














1 Answer
1






active

oldest

votes


















0














In direct answer why it doesn't update the percentage field...it doesn't appear that you're actually writing to any percentage field. Even then, it's likely your update statement updated zero rows. Are you sure you're updating...and not wanting to insert instead? Are you 100% certain that the target row exists in the database?



In the comments, people are telling you that you're open to a SQL injection attack...meaning it's possible that somebody could enter a SQL command into one of the text boxes...and read or destroy your data.



To prevent this, it's common practice to rely on the SQL client layer to protect your query. To do that, you need to make a query with replaceable variables, and pass values for those variables. The query would look like this:



var query = @"
update Registration set
FirstName = @FirstName,
LastName = @LastName,
EmailID = @EmailID,
MobileNumber = @MobileNumber,
Class = @Class,
Stream = @Stream
where
ID = @ID"


This may look like an odd string, but the SQL client layer knows how to replace the variables with values. It will do everything you need...you don't have to put quotes around the variables or anything. You just need to pass values for the variables. And that looks like this:



//--> note: it would be worthwhile to NOT have the definition
//--> of the connection string right in the method. It would be better
//--> to store it in a safe, reusable location...
//--> your application settings, for example
var connectionString = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";

//--> By the way...your conn and cmd are disposable (meaning they're
//--> expensive to NOT clean up when your done with them).
//--> They should be used in a 'using' block or a try/finally construct.
//--> Just using Open/Close isn't really good practice, because if there's
//--> a SQL error, your connection would not be closed.
using ( var conn = new SqlConnection( connectionString )
{
using ( var cmd = conn.CreateCommand( ) )
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue( "@ID", ID );
cmd.Parameters.AddWithValue( "@FirstName", FirstName );
cmd.Parameters.AddWithValue( "@LastName", LastName );
cmd.Parameters.AddWithValue( "@EmailId", EmailId );
cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
cmd.Parameters.AddWithValue( "@Class", Class );
cmd.Parameters.AddWithValue( "@Stream", Stream );

var numberOfRowsUpdated = cmd.ExecuteNonQuery();
if ( numberOfRowsUpdated != 1 )
{
throw new InvalidOperationException( "Oh no!!");
}
}
}


If numberOfRowsUpdated is anything but 1, you have a problem...but at least you have some diagnostic information to help you know you have a problem.



Let's think a little bit about getting data from the form. It's not that uncommon to take whatever the default name your IDE assigns to the controls (Label1, Text1, Text2, etc.), but your code will be far more readable and therefore maintainable if you give them meaningful names.



Assuming you're going to be writing more code, to do ever more interesting things with your grid values, you could invest in writing a helper method or even just make an extra variable to get the noise out of your more serious methods. You'd want to target the highly-repeated phrases.



For example, if you make a variable called row that contains the current row, it makes the following lines a little easier to read, understand, and maintain:



var row = GridView1.Rows[e.RowIndex];
var ID = int.Parse((Label) row.FindControl("Label1")).Text;
var FirstName = ((TextBox) row.FindControl("Text2")).Text;
var LastName = ((TextBox) row.FindControl("Text3")).Text;
//--> and so on...


But even then, there's still a lot of repeating noise. How to cook that down? In your case, we could make a method and pass the grid row and the name, and get back a string value. Maybe something like:



private static string CellValue( GridViewRow gridViewRow, string cellName )
{
//--> note: Label and TextBox implement the ITextControl interface...
var control = gridViewRow.FindControl( cellName ) as ITextControl;
if ( control != null )
{
return control.Text;
}
else
{
//--> handle non-text controls or throw exception...
throw new InvalidOperationException( "This didn't work: " + cellName );
}
}


...and then your main code starts to look nicer:



var row =  GridView1.Rows[e.RowIndex];
var ID = int.Parse( CellValue( row, "Label1" ) );
var FirstName = CellValue( row, "Text2" );
var LastName = CellValue( row, "Text3" );
var EmailId = CellValue( row, "Text4" );
var MobileNumber = CellValue( row, "Text5" );
var Class = CellValue( row, "Text6" );
var Stream = CellValue( row, "Text7" );


Notice that now, the name of the control is very near to the name of the variable...so it's easier to see which variables come from which controls.



Putting it all together (without all the commentary), you'd have something like:



static string ConnectionString
{
get
{
return = @"
Data Source=USER-PC\LOCAL;
Initial Catalog=STUDENT;
Integrated Security=True";
}
}

static string CellValue( GridViewRow gridViewRow, string cellName )
{
var control = gridViewRow.FindControl( cellName ) as ITextControl;
if ( control != null )
{
return control.Text;
}
else
{
throw new InvalidOperationException( "This didn't work: " + cellName );
}
}

protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
{
var row = GridView1.Rows[e.RowIndex];
var ID = int.Parse( CellValue( row, "Label1" ) );
var FirstName = CellValue( row, "Text2" );
var LastName = CellValue( row, "Text3" );
var EmailId = CellValue( row, "Text4" );
var MobileNumber = CellValue( row, "Text5" );
var Class = CellValue( row, "Text6" );
var Stream = CellValue( row, "Text7" );

var query = @"
update Registration set
FirstName = @FirstName,
LastName = @LastName,
EmailID = @EmailID,
MobileNumber = @MobileNumber,
Class = @Class,
Stream = @Stream
where
ID = @ID"

using ( var conn = new SqlConnection( ConnectionString )
{
using ( var cmd = conn.CreateCommand( ) )
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue( "@ID", ID );
cmd.Parameters.AddWithValue( "@FirstName", FirstName );
cmd.Parameters.AddWithValue( "@LastName", LastName );
cmd.Parameters.AddWithValue( "@EmailId", EmailId );
cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
cmd.Parameters.AddWithValue( "@Class", Class );
cmd.Parameters.AddWithValue( "@Stream", Stream );

var numberOfRowsUpdated = cmd.ExecuteNonQuery();
if ( numberOfRowsUpdated != 1 )
{
throw new InvalidOperationException( "Oh no!!");
}
}
}
}


It's possible that none of what I put in here solves your problem...but you're more likely to solve the problem when you can make little pieces of code that will tell you more about what's going on.



So, focus on:




  • making your code safe to call

  • getting the noise out of your main methods

  • making diagnostic values that you can check

  • throwing exceptions when things go wrong


Don't be afraid to format your text more vertically to clearly see what's going on. A method shouldn't be longer than what can fit on the screen, but making it run off the screen to the right is kinda cheating (IMHO).






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455117%2fthe-query-executes-fine-but-the-problem-is-that-when-this-query-executes-and-it%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    In direct answer why it doesn't update the percentage field...it doesn't appear that you're actually writing to any percentage field. Even then, it's likely your update statement updated zero rows. Are you sure you're updating...and not wanting to insert instead? Are you 100% certain that the target row exists in the database?



    In the comments, people are telling you that you're open to a SQL injection attack...meaning it's possible that somebody could enter a SQL command into one of the text boxes...and read or destroy your data.



    To prevent this, it's common practice to rely on the SQL client layer to protect your query. To do that, you need to make a query with replaceable variables, and pass values for those variables. The query would look like this:



    var query = @"
    update Registration set
    FirstName = @FirstName,
    LastName = @LastName,
    EmailID = @EmailID,
    MobileNumber = @MobileNumber,
    Class = @Class,
    Stream = @Stream
    where
    ID = @ID"


    This may look like an odd string, but the SQL client layer knows how to replace the variables with values. It will do everything you need...you don't have to put quotes around the variables or anything. You just need to pass values for the variables. And that looks like this:



    //--> note: it would be worthwhile to NOT have the definition
    //--> of the connection string right in the method. It would be better
    //--> to store it in a safe, reusable location...
    //--> your application settings, for example
    var connectionString = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";

    //--> By the way...your conn and cmd are disposable (meaning they're
    //--> expensive to NOT clean up when your done with them).
    //--> They should be used in a 'using' block or a try/finally construct.
    //--> Just using Open/Close isn't really good practice, because if there's
    //--> a SQL error, your connection would not be closed.
    using ( var conn = new SqlConnection( connectionString )
    {
    using ( var cmd = conn.CreateCommand( ) )
    {
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = query;
    cmd.Parameters.AddWithValue( "@ID", ID );
    cmd.Parameters.AddWithValue( "@FirstName", FirstName );
    cmd.Parameters.AddWithValue( "@LastName", LastName );
    cmd.Parameters.AddWithValue( "@EmailId", EmailId );
    cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
    cmd.Parameters.AddWithValue( "@Class", Class );
    cmd.Parameters.AddWithValue( "@Stream", Stream );

    var numberOfRowsUpdated = cmd.ExecuteNonQuery();
    if ( numberOfRowsUpdated != 1 )
    {
    throw new InvalidOperationException( "Oh no!!");
    }
    }
    }


    If numberOfRowsUpdated is anything but 1, you have a problem...but at least you have some diagnostic information to help you know you have a problem.



    Let's think a little bit about getting data from the form. It's not that uncommon to take whatever the default name your IDE assigns to the controls (Label1, Text1, Text2, etc.), but your code will be far more readable and therefore maintainable if you give them meaningful names.



    Assuming you're going to be writing more code, to do ever more interesting things with your grid values, you could invest in writing a helper method or even just make an extra variable to get the noise out of your more serious methods. You'd want to target the highly-repeated phrases.



    For example, if you make a variable called row that contains the current row, it makes the following lines a little easier to read, understand, and maintain:



    var row = GridView1.Rows[e.RowIndex];
    var ID = int.Parse((Label) row.FindControl("Label1")).Text;
    var FirstName = ((TextBox) row.FindControl("Text2")).Text;
    var LastName = ((TextBox) row.FindControl("Text3")).Text;
    //--> and so on...


    But even then, there's still a lot of repeating noise. How to cook that down? In your case, we could make a method and pass the grid row and the name, and get back a string value. Maybe something like:



    private static string CellValue( GridViewRow gridViewRow, string cellName )
    {
    //--> note: Label and TextBox implement the ITextControl interface...
    var control = gridViewRow.FindControl( cellName ) as ITextControl;
    if ( control != null )
    {
    return control.Text;
    }
    else
    {
    //--> handle non-text controls or throw exception...
    throw new InvalidOperationException( "This didn't work: " + cellName );
    }
    }


    ...and then your main code starts to look nicer:



    var row =  GridView1.Rows[e.RowIndex];
    var ID = int.Parse( CellValue( row, "Label1" ) );
    var FirstName = CellValue( row, "Text2" );
    var LastName = CellValue( row, "Text3" );
    var EmailId = CellValue( row, "Text4" );
    var MobileNumber = CellValue( row, "Text5" );
    var Class = CellValue( row, "Text6" );
    var Stream = CellValue( row, "Text7" );


    Notice that now, the name of the control is very near to the name of the variable...so it's easier to see which variables come from which controls.



    Putting it all together (without all the commentary), you'd have something like:



    static string ConnectionString
    {
    get
    {
    return = @"
    Data Source=USER-PC\LOCAL;
    Initial Catalog=STUDENT;
    Integrated Security=True";
    }
    }

    static string CellValue( GridViewRow gridViewRow, string cellName )
    {
    var control = gridViewRow.FindControl( cellName ) as ITextControl;
    if ( control != null )
    {
    return control.Text;
    }
    else
    {
    throw new InvalidOperationException( "This didn't work: " + cellName );
    }
    }

    protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
    {
    var row = GridView1.Rows[e.RowIndex];
    var ID = int.Parse( CellValue( row, "Label1" ) );
    var FirstName = CellValue( row, "Text2" );
    var LastName = CellValue( row, "Text3" );
    var EmailId = CellValue( row, "Text4" );
    var MobileNumber = CellValue( row, "Text5" );
    var Class = CellValue( row, "Text6" );
    var Stream = CellValue( row, "Text7" );

    var query = @"
    update Registration set
    FirstName = @FirstName,
    LastName = @LastName,
    EmailID = @EmailID,
    MobileNumber = @MobileNumber,
    Class = @Class,
    Stream = @Stream
    where
    ID = @ID"

    using ( var conn = new SqlConnection( ConnectionString )
    {
    using ( var cmd = conn.CreateCommand( ) )
    {
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = query;
    cmd.Parameters.AddWithValue( "@ID", ID );
    cmd.Parameters.AddWithValue( "@FirstName", FirstName );
    cmd.Parameters.AddWithValue( "@LastName", LastName );
    cmd.Parameters.AddWithValue( "@EmailId", EmailId );
    cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
    cmd.Parameters.AddWithValue( "@Class", Class );
    cmd.Parameters.AddWithValue( "@Stream", Stream );

    var numberOfRowsUpdated = cmd.ExecuteNonQuery();
    if ( numberOfRowsUpdated != 1 )
    {
    throw new InvalidOperationException( "Oh no!!");
    }
    }
    }
    }


    It's possible that none of what I put in here solves your problem...but you're more likely to solve the problem when you can make little pieces of code that will tell you more about what's going on.



    So, focus on:




    • making your code safe to call

    • getting the noise out of your main methods

    • making diagnostic values that you can check

    • throwing exceptions when things go wrong


    Don't be afraid to format your text more vertically to clearly see what's going on. A method shouldn't be longer than what can fit on the screen, but making it run off the screen to the right is kinda cheating (IMHO).






    share|improve this answer






























      0














      In direct answer why it doesn't update the percentage field...it doesn't appear that you're actually writing to any percentage field. Even then, it's likely your update statement updated zero rows. Are you sure you're updating...and not wanting to insert instead? Are you 100% certain that the target row exists in the database?



      In the comments, people are telling you that you're open to a SQL injection attack...meaning it's possible that somebody could enter a SQL command into one of the text boxes...and read or destroy your data.



      To prevent this, it's common practice to rely on the SQL client layer to protect your query. To do that, you need to make a query with replaceable variables, and pass values for those variables. The query would look like this:



      var query = @"
      update Registration set
      FirstName = @FirstName,
      LastName = @LastName,
      EmailID = @EmailID,
      MobileNumber = @MobileNumber,
      Class = @Class,
      Stream = @Stream
      where
      ID = @ID"


      This may look like an odd string, but the SQL client layer knows how to replace the variables with values. It will do everything you need...you don't have to put quotes around the variables or anything. You just need to pass values for the variables. And that looks like this:



      //--> note: it would be worthwhile to NOT have the definition
      //--> of the connection string right in the method. It would be better
      //--> to store it in a safe, reusable location...
      //--> your application settings, for example
      var connectionString = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";

      //--> By the way...your conn and cmd are disposable (meaning they're
      //--> expensive to NOT clean up when your done with them).
      //--> They should be used in a 'using' block or a try/finally construct.
      //--> Just using Open/Close isn't really good practice, because if there's
      //--> a SQL error, your connection would not be closed.
      using ( var conn = new SqlConnection( connectionString )
      {
      using ( var cmd = conn.CreateCommand( ) )
      {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = query;
      cmd.Parameters.AddWithValue( "@ID", ID );
      cmd.Parameters.AddWithValue( "@FirstName", FirstName );
      cmd.Parameters.AddWithValue( "@LastName", LastName );
      cmd.Parameters.AddWithValue( "@EmailId", EmailId );
      cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
      cmd.Parameters.AddWithValue( "@Class", Class );
      cmd.Parameters.AddWithValue( "@Stream", Stream );

      var numberOfRowsUpdated = cmd.ExecuteNonQuery();
      if ( numberOfRowsUpdated != 1 )
      {
      throw new InvalidOperationException( "Oh no!!");
      }
      }
      }


      If numberOfRowsUpdated is anything but 1, you have a problem...but at least you have some diagnostic information to help you know you have a problem.



      Let's think a little bit about getting data from the form. It's not that uncommon to take whatever the default name your IDE assigns to the controls (Label1, Text1, Text2, etc.), but your code will be far more readable and therefore maintainable if you give them meaningful names.



      Assuming you're going to be writing more code, to do ever more interesting things with your grid values, you could invest in writing a helper method or even just make an extra variable to get the noise out of your more serious methods. You'd want to target the highly-repeated phrases.



      For example, if you make a variable called row that contains the current row, it makes the following lines a little easier to read, understand, and maintain:



      var row = GridView1.Rows[e.RowIndex];
      var ID = int.Parse((Label) row.FindControl("Label1")).Text;
      var FirstName = ((TextBox) row.FindControl("Text2")).Text;
      var LastName = ((TextBox) row.FindControl("Text3")).Text;
      //--> and so on...


      But even then, there's still a lot of repeating noise. How to cook that down? In your case, we could make a method and pass the grid row and the name, and get back a string value. Maybe something like:



      private static string CellValue( GridViewRow gridViewRow, string cellName )
      {
      //--> note: Label and TextBox implement the ITextControl interface...
      var control = gridViewRow.FindControl( cellName ) as ITextControl;
      if ( control != null )
      {
      return control.Text;
      }
      else
      {
      //--> handle non-text controls or throw exception...
      throw new InvalidOperationException( "This didn't work: " + cellName );
      }
      }


      ...and then your main code starts to look nicer:



      var row =  GridView1.Rows[e.RowIndex];
      var ID = int.Parse( CellValue( row, "Label1" ) );
      var FirstName = CellValue( row, "Text2" );
      var LastName = CellValue( row, "Text3" );
      var EmailId = CellValue( row, "Text4" );
      var MobileNumber = CellValue( row, "Text5" );
      var Class = CellValue( row, "Text6" );
      var Stream = CellValue( row, "Text7" );


      Notice that now, the name of the control is very near to the name of the variable...so it's easier to see which variables come from which controls.



      Putting it all together (without all the commentary), you'd have something like:



      static string ConnectionString
      {
      get
      {
      return = @"
      Data Source=USER-PC\LOCAL;
      Initial Catalog=STUDENT;
      Integrated Security=True";
      }
      }

      static string CellValue( GridViewRow gridViewRow, string cellName )
      {
      var control = gridViewRow.FindControl( cellName ) as ITextControl;
      if ( control != null )
      {
      return control.Text;
      }
      else
      {
      throw new InvalidOperationException( "This didn't work: " + cellName );
      }
      }

      protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
      {
      var row = GridView1.Rows[e.RowIndex];
      var ID = int.Parse( CellValue( row, "Label1" ) );
      var FirstName = CellValue( row, "Text2" );
      var LastName = CellValue( row, "Text3" );
      var EmailId = CellValue( row, "Text4" );
      var MobileNumber = CellValue( row, "Text5" );
      var Class = CellValue( row, "Text6" );
      var Stream = CellValue( row, "Text7" );

      var query = @"
      update Registration set
      FirstName = @FirstName,
      LastName = @LastName,
      EmailID = @EmailID,
      MobileNumber = @MobileNumber,
      Class = @Class,
      Stream = @Stream
      where
      ID = @ID"

      using ( var conn = new SqlConnection( ConnectionString )
      {
      using ( var cmd = conn.CreateCommand( ) )
      {
      cmd.CommandType = CommandType.Text;
      cmd.CommandText = query;
      cmd.Parameters.AddWithValue( "@ID", ID );
      cmd.Parameters.AddWithValue( "@FirstName", FirstName );
      cmd.Parameters.AddWithValue( "@LastName", LastName );
      cmd.Parameters.AddWithValue( "@EmailId", EmailId );
      cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
      cmd.Parameters.AddWithValue( "@Class", Class );
      cmd.Parameters.AddWithValue( "@Stream", Stream );

      var numberOfRowsUpdated = cmd.ExecuteNonQuery();
      if ( numberOfRowsUpdated != 1 )
      {
      throw new InvalidOperationException( "Oh no!!");
      }
      }
      }
      }


      It's possible that none of what I put in here solves your problem...but you're more likely to solve the problem when you can make little pieces of code that will tell you more about what's going on.



      So, focus on:




      • making your code safe to call

      • getting the noise out of your main methods

      • making diagnostic values that you can check

      • throwing exceptions when things go wrong


      Don't be afraid to format your text more vertically to clearly see what's going on. A method shouldn't be longer than what can fit on the screen, but making it run off the screen to the right is kinda cheating (IMHO).






      share|improve this answer




























        0












        0








        0







        In direct answer why it doesn't update the percentage field...it doesn't appear that you're actually writing to any percentage field. Even then, it's likely your update statement updated zero rows. Are you sure you're updating...and not wanting to insert instead? Are you 100% certain that the target row exists in the database?



        In the comments, people are telling you that you're open to a SQL injection attack...meaning it's possible that somebody could enter a SQL command into one of the text boxes...and read or destroy your data.



        To prevent this, it's common practice to rely on the SQL client layer to protect your query. To do that, you need to make a query with replaceable variables, and pass values for those variables. The query would look like this:



        var query = @"
        update Registration set
        FirstName = @FirstName,
        LastName = @LastName,
        EmailID = @EmailID,
        MobileNumber = @MobileNumber,
        Class = @Class,
        Stream = @Stream
        where
        ID = @ID"


        This may look like an odd string, but the SQL client layer knows how to replace the variables with values. It will do everything you need...you don't have to put quotes around the variables or anything. You just need to pass values for the variables. And that looks like this:



        //--> note: it would be worthwhile to NOT have the definition
        //--> of the connection string right in the method. It would be better
        //--> to store it in a safe, reusable location...
        //--> your application settings, for example
        var connectionString = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";

        //--> By the way...your conn and cmd are disposable (meaning they're
        //--> expensive to NOT clean up when your done with them).
        //--> They should be used in a 'using' block or a try/finally construct.
        //--> Just using Open/Close isn't really good practice, because if there's
        //--> a SQL error, your connection would not be closed.
        using ( var conn = new SqlConnection( connectionString )
        {
        using ( var cmd = conn.CreateCommand( ) )
        {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.Parameters.AddWithValue( "@ID", ID );
        cmd.Parameters.AddWithValue( "@FirstName", FirstName );
        cmd.Parameters.AddWithValue( "@LastName", LastName );
        cmd.Parameters.AddWithValue( "@EmailId", EmailId );
        cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
        cmd.Parameters.AddWithValue( "@Class", Class );
        cmd.Parameters.AddWithValue( "@Stream", Stream );

        var numberOfRowsUpdated = cmd.ExecuteNonQuery();
        if ( numberOfRowsUpdated != 1 )
        {
        throw new InvalidOperationException( "Oh no!!");
        }
        }
        }


        If numberOfRowsUpdated is anything but 1, you have a problem...but at least you have some diagnostic information to help you know you have a problem.



        Let's think a little bit about getting data from the form. It's not that uncommon to take whatever the default name your IDE assigns to the controls (Label1, Text1, Text2, etc.), but your code will be far more readable and therefore maintainable if you give them meaningful names.



        Assuming you're going to be writing more code, to do ever more interesting things with your grid values, you could invest in writing a helper method or even just make an extra variable to get the noise out of your more serious methods. You'd want to target the highly-repeated phrases.



        For example, if you make a variable called row that contains the current row, it makes the following lines a little easier to read, understand, and maintain:



        var row = GridView1.Rows[e.RowIndex];
        var ID = int.Parse((Label) row.FindControl("Label1")).Text;
        var FirstName = ((TextBox) row.FindControl("Text2")).Text;
        var LastName = ((TextBox) row.FindControl("Text3")).Text;
        //--> and so on...


        But even then, there's still a lot of repeating noise. How to cook that down? In your case, we could make a method and pass the grid row and the name, and get back a string value. Maybe something like:



        private static string CellValue( GridViewRow gridViewRow, string cellName )
        {
        //--> note: Label and TextBox implement the ITextControl interface...
        var control = gridViewRow.FindControl( cellName ) as ITextControl;
        if ( control != null )
        {
        return control.Text;
        }
        else
        {
        //--> handle non-text controls or throw exception...
        throw new InvalidOperationException( "This didn't work: " + cellName );
        }
        }


        ...and then your main code starts to look nicer:



        var row =  GridView1.Rows[e.RowIndex];
        var ID = int.Parse( CellValue( row, "Label1" ) );
        var FirstName = CellValue( row, "Text2" );
        var LastName = CellValue( row, "Text3" );
        var EmailId = CellValue( row, "Text4" );
        var MobileNumber = CellValue( row, "Text5" );
        var Class = CellValue( row, "Text6" );
        var Stream = CellValue( row, "Text7" );


        Notice that now, the name of the control is very near to the name of the variable...so it's easier to see which variables come from which controls.



        Putting it all together (without all the commentary), you'd have something like:



        static string ConnectionString
        {
        get
        {
        return = @"
        Data Source=USER-PC\LOCAL;
        Initial Catalog=STUDENT;
        Integrated Security=True";
        }
        }

        static string CellValue( GridViewRow gridViewRow, string cellName )
        {
        var control = gridViewRow.FindControl( cellName ) as ITextControl;
        if ( control != null )
        {
        return control.Text;
        }
        else
        {
        throw new InvalidOperationException( "This didn't work: " + cellName );
        }
        }

        protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
        {
        var row = GridView1.Rows[e.RowIndex];
        var ID = int.Parse( CellValue( row, "Label1" ) );
        var FirstName = CellValue( row, "Text2" );
        var LastName = CellValue( row, "Text3" );
        var EmailId = CellValue( row, "Text4" );
        var MobileNumber = CellValue( row, "Text5" );
        var Class = CellValue( row, "Text6" );
        var Stream = CellValue( row, "Text7" );

        var query = @"
        update Registration set
        FirstName = @FirstName,
        LastName = @LastName,
        EmailID = @EmailID,
        MobileNumber = @MobileNumber,
        Class = @Class,
        Stream = @Stream
        where
        ID = @ID"

        using ( var conn = new SqlConnection( ConnectionString )
        {
        using ( var cmd = conn.CreateCommand( ) )
        {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.Parameters.AddWithValue( "@ID", ID );
        cmd.Parameters.AddWithValue( "@FirstName", FirstName );
        cmd.Parameters.AddWithValue( "@LastName", LastName );
        cmd.Parameters.AddWithValue( "@EmailId", EmailId );
        cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
        cmd.Parameters.AddWithValue( "@Class", Class );
        cmd.Parameters.AddWithValue( "@Stream", Stream );

        var numberOfRowsUpdated = cmd.ExecuteNonQuery();
        if ( numberOfRowsUpdated != 1 )
        {
        throw new InvalidOperationException( "Oh no!!");
        }
        }
        }
        }


        It's possible that none of what I put in here solves your problem...but you're more likely to solve the problem when you can make little pieces of code that will tell you more about what's going on.



        So, focus on:




        • making your code safe to call

        • getting the noise out of your main methods

        • making diagnostic values that you can check

        • throwing exceptions when things go wrong


        Don't be afraid to format your text more vertically to clearly see what's going on. A method shouldn't be longer than what can fit on the screen, but making it run off the screen to the right is kinda cheating (IMHO).






        share|improve this answer















        In direct answer why it doesn't update the percentage field...it doesn't appear that you're actually writing to any percentage field. Even then, it's likely your update statement updated zero rows. Are you sure you're updating...and not wanting to insert instead? Are you 100% certain that the target row exists in the database?



        In the comments, people are telling you that you're open to a SQL injection attack...meaning it's possible that somebody could enter a SQL command into one of the text boxes...and read or destroy your data.



        To prevent this, it's common practice to rely on the SQL client layer to protect your query. To do that, you need to make a query with replaceable variables, and pass values for those variables. The query would look like this:



        var query = @"
        update Registration set
        FirstName = @FirstName,
        LastName = @LastName,
        EmailID = @EmailID,
        MobileNumber = @MobileNumber,
        Class = @Class,
        Stream = @Stream
        where
        ID = @ID"


        This may look like an odd string, but the SQL client layer knows how to replace the variables with values. It will do everything you need...you don't have to put quotes around the variables or anything. You just need to pass values for the variables. And that looks like this:



        //--> note: it would be worthwhile to NOT have the definition
        //--> of the connection string right in the method. It would be better
        //--> to store it in a safe, reusable location...
        //--> your application settings, for example
        var connectionString = "Data Source=USER-PC\LOCAL;Initial Catalog=STUDENT;Integrated Security=True";

        //--> By the way...your conn and cmd are disposable (meaning they're
        //--> expensive to NOT clean up when your done with them).
        //--> They should be used in a 'using' block or a try/finally construct.
        //--> Just using Open/Close isn't really good practice, because if there's
        //--> a SQL error, your connection would not be closed.
        using ( var conn = new SqlConnection( connectionString )
        {
        using ( var cmd = conn.CreateCommand( ) )
        {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.Parameters.AddWithValue( "@ID", ID );
        cmd.Parameters.AddWithValue( "@FirstName", FirstName );
        cmd.Parameters.AddWithValue( "@LastName", LastName );
        cmd.Parameters.AddWithValue( "@EmailId", EmailId );
        cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
        cmd.Parameters.AddWithValue( "@Class", Class );
        cmd.Parameters.AddWithValue( "@Stream", Stream );

        var numberOfRowsUpdated = cmd.ExecuteNonQuery();
        if ( numberOfRowsUpdated != 1 )
        {
        throw new InvalidOperationException( "Oh no!!");
        }
        }
        }


        If numberOfRowsUpdated is anything but 1, you have a problem...but at least you have some diagnostic information to help you know you have a problem.



        Let's think a little bit about getting data from the form. It's not that uncommon to take whatever the default name your IDE assigns to the controls (Label1, Text1, Text2, etc.), but your code will be far more readable and therefore maintainable if you give them meaningful names.



        Assuming you're going to be writing more code, to do ever more interesting things with your grid values, you could invest in writing a helper method or even just make an extra variable to get the noise out of your more serious methods. You'd want to target the highly-repeated phrases.



        For example, if you make a variable called row that contains the current row, it makes the following lines a little easier to read, understand, and maintain:



        var row = GridView1.Rows[e.RowIndex];
        var ID = int.Parse((Label) row.FindControl("Label1")).Text;
        var FirstName = ((TextBox) row.FindControl("Text2")).Text;
        var LastName = ((TextBox) row.FindControl("Text3")).Text;
        //--> and so on...


        But even then, there's still a lot of repeating noise. How to cook that down? In your case, we could make a method and pass the grid row and the name, and get back a string value. Maybe something like:



        private static string CellValue( GridViewRow gridViewRow, string cellName )
        {
        //--> note: Label and TextBox implement the ITextControl interface...
        var control = gridViewRow.FindControl( cellName ) as ITextControl;
        if ( control != null )
        {
        return control.Text;
        }
        else
        {
        //--> handle non-text controls or throw exception...
        throw new InvalidOperationException( "This didn't work: " + cellName );
        }
        }


        ...and then your main code starts to look nicer:



        var row =  GridView1.Rows[e.RowIndex];
        var ID = int.Parse( CellValue( row, "Label1" ) );
        var FirstName = CellValue( row, "Text2" );
        var LastName = CellValue( row, "Text3" );
        var EmailId = CellValue( row, "Text4" );
        var MobileNumber = CellValue( row, "Text5" );
        var Class = CellValue( row, "Text6" );
        var Stream = CellValue( row, "Text7" );


        Notice that now, the name of the control is very near to the name of the variable...so it's easier to see which variables come from which controls.



        Putting it all together (without all the commentary), you'd have something like:



        static string ConnectionString
        {
        get
        {
        return = @"
        Data Source=USER-PC\LOCAL;
        Initial Catalog=STUDENT;
        Integrated Security=True";
        }
        }

        static string CellValue( GridViewRow gridViewRow, string cellName )
        {
        var control = gridViewRow.FindControl( cellName ) as ITextControl;
        if ( control != null )
        {
        return control.Text;
        }
        else
        {
        throw new InvalidOperationException( "This didn't work: " + cellName );
        }
        }

        protected void GridView1_RowUpdating1(object sender, GridViewUpdateEventArgs e)
        {
        var row = GridView1.Rows[e.RowIndex];
        var ID = int.Parse( CellValue( row, "Label1" ) );
        var FirstName = CellValue( row, "Text2" );
        var LastName = CellValue( row, "Text3" );
        var EmailId = CellValue( row, "Text4" );
        var MobileNumber = CellValue( row, "Text5" );
        var Class = CellValue( row, "Text6" );
        var Stream = CellValue( row, "Text7" );

        var query = @"
        update Registration set
        FirstName = @FirstName,
        LastName = @LastName,
        EmailID = @EmailID,
        MobileNumber = @MobileNumber,
        Class = @Class,
        Stream = @Stream
        where
        ID = @ID"

        using ( var conn = new SqlConnection( ConnectionString )
        {
        using ( var cmd = conn.CreateCommand( ) )
        {
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = query;
        cmd.Parameters.AddWithValue( "@ID", ID );
        cmd.Parameters.AddWithValue( "@FirstName", FirstName );
        cmd.Parameters.AddWithValue( "@LastName", LastName );
        cmd.Parameters.AddWithValue( "@EmailId", EmailId );
        cmd.Parameters.AddWithValue( "@MobileNumber", MobileNumber );
        cmd.Parameters.AddWithValue( "@Class", Class );
        cmd.Parameters.AddWithValue( "@Stream", Stream );

        var numberOfRowsUpdated = cmd.ExecuteNonQuery();
        if ( numberOfRowsUpdated != 1 )
        {
        throw new InvalidOperationException( "Oh no!!");
        }
        }
        }
        }


        It's possible that none of what I put in here solves your problem...but you're more likely to solve the problem when you can make little pieces of code that will tell you more about what's going on.



        So, focus on:




        • making your code safe to call

        • getting the noise out of your main methods

        • making diagnostic values that you can check

        • throwing exceptions when things go wrong


        Don't be afraid to format your text more vertically to clearly see what's going on. A method shouldn't be longer than what can fit on the screen, but making it run off the screen to the right is kinda cheating (IMHO).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 24 '18 at 14:24

























        answered Nov 24 '18 at 13:49









        ClayClay

        2,87611634




        2,87611634






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53455117%2fthe-query-executes-fine-but-the-problem-is-that-when-this-query-executes-and-it%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)