Link to home
Start Free TrialLog in
Avatar of jung1975
jung1975

asked on

Gridview and update columns progrmatically

I have a grid view looks like below. I am trying to make Column A and B as the calculated column and C as the input column.
Let's say. As I enter a number in the column C and click calculate button, it will automatically insert numbers into column A and B based on the fomular ( A = C * key and B = C + key ) and gives me the option that I can choose either update( A,B, and C) or cancel. How can I do this? Any examples that I can look at it?

                      Key       A   B   C
Update Cancel  36                      Calculate
Edit                  37                     Calculate
Edit                  38                     Calculate
Edit                  39                     Calculate
Edit                  40                     Calculate
Avatar of Jason Scolaro
Jason Scolaro
Flag of United States of America image

Hi jung1975,

I would put your code for the Calculate click in the RowCommand event.  Basically something like:

If e.CommandArgument = "Calculate" Then
    Dim LabelA As Label = CType(e.Row.FindControl("LabelA"), Label)
    Dim LabelB As Label = CType(e.Row.FindControl("LabelB"), Label)
    Dim TextBoxC As TextBox = CType(e.Row.FindControl("TextBoxC"), TextBox)
    Dim Key As Integer = CInt(CType(e.Row.FindControl("KeyLabel"), Label))

    LabelA.Text = CStr(CInt(TextBoxC.Text.Trim) * Key)
    LabelB.Text = CStr(CInt(TextBoxC.Text.Trim) + Key)
End If

Hopefully you can put the rest together.  Let me know if you have any questions.

-- Jason
Avatar of jung1975
jung1975

ASKER

Hi!

Do I have to add label and text box to be able to do this?

 I am using C# and I was thiking that I can create column A, B and C programtically by using clientside event handler...

What I am trying to do is to make  A,B,C and Calculate column show up dynamically( client side) as soon as user click edit buttion in Gridview ,and  if a user enters the number in column C and click calculate button, the calculated numbers are displayed in column A and B, after that user will have the option to choose whether he/she s going to save those values in database or not....

No need to add them dynamically, just create them on the HTML side of things but set their Visible property to FALSE.  Then within your EditCommand event, toggle the Visible Property to TRUE.

Hopefully that helps.  Good luck!
-- Jason
Is there any C# example?
jung1975,

The syntax would be:
GridView.Columns[2].Visible = true; // enable the A column

This is assuming that the A column is the 3rd column (index 2).

My above code, in C#:

if (e.CommandArgument == "Calculate") {
    Label LabelA = (Label)e.Row.FindControl("LabelA");
    Label LabelB = (Label)e.Row.FindControl("LabelB");
    TextBox TextBoxC = (TextBox)e.Row.FindControl("TextBoxC");
    int Key = (int)((Label)e.Row.FindControl("KeyLabel")).Text;

    LabelA.Text = ((int)TextBoxC.Text.Trim) * Key;
    LabelB.Text = ((int)TextBoxC.Text.Trim) + Key;
}

HTH -- Good luck!
-- Jason
Thanks,but I am using a gridview and all of three columns are in EditTemplate field in gridview....  how can I do the same things in a gridview?

<asp:TemplateField HeaderText="Enter Number">
                    <EditItemTemplate>
                        <strong> </strong><asp:TextBox ID="TextBox1" runat="server" BackColor="PaleGoldenrod" Width="127px"></asp:TextBox>
                    </EditItemTemplate>
                    <ItemStyle Width="100px" Wrap="True" />
                </asp:TemplateField
and I am getting an error says: GridViewCommandEventArgs  does not contain a definition of ROW...
Warning      1      Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'      
Error      2      'System.Web.UI.WebControls.GridViewCommandEventArgs' does not contain a definition for 'Row'      
Error      6      Cannot convert method group 'Trim' to non-delegate type 'int'. Did you intend to invoke the method
jung1975,

It appears that the GridViewCommandEventArgs doesn't have the Row property.  So we'll have to grab it another way....
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];

Then anywhere you see "e.Row" you can replace simply with "row".

As far as the Trim goes, I believe you only need to add the open and close parenthesis' to the end of the word Trim.  Otherwise you could use these lines:
LabelA.Text = Convert.ToInt32(TextBoxC.Text.Trim()) * Key;
LabelB.Text = Convert.ToInt32(TextBoxC.Text.Trim()) + Key;

Hope that helps.
-- Jason
Hi! Jason,

I wrote the below code to do some quick test..but I am getting an error says
" int index = Convert.ToInt32(e.CommandArgument);  Input string was not in a correct format."

What I am doing wrong here? Imagebutton is in EditItemTemplate in Gridview.

protected void ImageButton1_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandName == "ImageButton1")
        {
            int index = Convert.ToInt32(e.CommandArgument);
           

            GridViewRow row = GridView1.Rows[index];


            Label Label1 = (Label)row.FindControl("Label1");
            TextBox TextBoxC = (TextBox)row.FindControl("TextBoxC");
            Label1.Text = "Hello";

        }
    }
jung1975,

The code I gave you must be placed inside the RowCommand event of the GridView.  Try placing your code in there and let's see what sort of results you get...

Good luck!
-- Jason
the whole purpose of this code is to let user enter the number in the textbox( Edititemtemplate)  in gridview and click the button ( image button) to populate  the calculated number on the label column automatically... so, I can't put the code in rowcommand event( if I put the whole code inside rowcommand event, nothing happens ) but Imagebutton_command event.
if i set the  commandargumnet of Imagebutton1 to 0, it works for only the first row...
jung1975,

When the ImageButton is clicked, two events should execute, the ImageButton's Command event and the RowCommand event.  We need to use the RowCommand because the Event argument for that event carries the Row that was clicked on.  You can't easily access that using the ImageButton's Command event argument.

In the RowCommand event, the CommandArgument holds the index of the row, that is why when you set the CommandArgument on the ImageButton it calculates for the 1st row (if you set it to 0).  

The next step right now is to figure out why the RowCommand event is firing.  Perhaps it is being overridden by the use of the ImageButton's Command event.

I hope that makes sense... good luck, you're close.
-- Jason
I meant to say "... why the RowCommand is _not_ firing."
Hi! Json,

Below is the code for gridview.

 "it is being overridden by the use of the ImageButton's Command event  " , so how can I prevent this behaviors?   Remember, the imagebutton is in the edititemtemplate... I am not sure this is something to do with it..

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
            DataSourceID="SqlDataSource1" Visible="False" Font-Names="Tahoma" Font-Size="9pt" Width="984px" OnRowEditing="GridView1_RowEditing" ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
            <FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
            <Columns>
                <asp:CommandField ButtonType="Image" CancelImageUrl="~/Image/icon-cancel.gif" EditImageUrl="~/Image/icon-tip.gif"
                    EditText="Select" ShowEditButton="True" UpdateImageUrl="~/Image/icon-save.gif"
                    UpdateText="Save" />
                <asp:BoundField DataField="financial_class_code" HeaderText="financial_class_code"
                    ReadOnly="True" SortExpression="financial_class_code" />
                <asp:BoundField DataField="financial_class_desc" HeaderText="financial_class_desc"
                    ReadOnly="True" SortExpression="financial_class_desc" />
                <asp:TemplateField HeaderText="Medical and UNH Issues">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" ></asp:Label>
                    </ItemTemplate>
                    <ItemStyle Width="200px" />
                </asp:TemplateField>
                <asp:BoundField DataField="Supp_Contractual_Allowances" HeaderText="Supp_Contractual_Allowances"
                    SortExpression="Supp_Contractual_Allowances">
                    <ControlStyle BackColor="Honeydew" />
                </asp:BoundField>
                <asp:BoundField DataField="Gross_revenue" HeaderText="Gross_revenue" SortExpression="Gross_revenue" ReadOnly="True" />
                <asp:TemplateField HeaderText="Enter Number">
                    <EditItemTemplate>
                        <strong> </strong><asp:TextBox ID="TextBox1" runat="server" BackColor="PaleGoldenrod" Width="127px"></asp:TextBox>
                    </EditItemTemplate>
                    <ItemStyle Width="100px" Wrap="True" />
                </asp:TemplateField>
                <asp:TemplateField>
                    <EditItemTemplate>
                        <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Image/Calculate.gif" />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="LightGray" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        </asp:GridView>


Here is code behind:
 protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ImageButton1")
        {
            int index = Convert.ToInt32(e.CommandArgument);


            GridViewRow row = GridView1.Rows[index];


            Label Label1 = (Label)row.FindControl("Label1");
            TextBox TextBoxC = (TextBox)row.FindControl("TextBoxC");
            Label1.Text = "Hello";

        }
    }
jung1975,

Add a CommandName to your ImageButton, like so:
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Image/Calculate.gif" CommandName="Calculate" />

Make sure to change this line of code:

 if (e.CommandName == "ImageButton1")
to this:
if (e.CommandName == "Calculate")

Good luck!
-- Jason
Hi! Jason,

 it looks like the Rowcommand event gets fire now, but I am still getting the same error when I debug the code
int index = Convert.ToInt32(e.CommandArgument); “Input string was not in a correct format"
I am not sure whta is causing this error? Do you have any idea?

    protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Calculate")
        {
            int index = Convert.ToInt32(e.CommandArgument);


            GridViewRow row = GridView1.Rows[index];


            Label Label1 = (Label)row.FindControl("Label1");
            TextBox TextBoxC = (TextBox)row.FindControl("TextBoxC");
            Label1.Text = "Hello";

        }
    }
jung1975,

OK... I think I've got it.. because we're not using the built-in ButtonField we have to program our CommandArgument ourselves... change your ImageButton to this:

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Image/Calculate.gif" CommandName="Calculate" CommandArgument='<%# Container.DataItemIndex %>' />

Give this a go.  It worked for me in my testing.

-- Jason
thanks Jason,
It works now.. but I still have some issues.
1) To be able to calculate the right value for Label1, I need to use a fomular : TextboxC( the number that user will enter) * GrossRevenue ( this fiield comes from database). Below is the updated code to be able to do that, but i am getting an error says : "Cannot implicitly convert type 'int' to 'string' "

2)User will need to save the value which is in Label1 to databse when they click save button( Edit command event) .
Do I have to use "GridViewUpdatedEventArgs" to be able to update the value( each row) which is in label1 to databse?
 I am not sure how to do this since the updatable value is in label1( EditItemtemplate). Can you give me some idea?



  protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Calculate")
        {
            int index = Convert.ToInt32(e.CommandArgument);


            GridViewRow row = GridView1.Rows[index];
            Label Label1 = (Label)row.FindControl("Label1");
            TextBox TextBoxC = (TextBox)row.FindControl("TextBoxC");
            int Grossrevenue = Convert.ToInt32(GridView1.Columns[5]);
         

            Label1.Text = (Grossrevenue) * Convert.ToInt32(TextBoxC.Text);
         


        }
    }
 
    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
       
    }

jung1975,

This line won't work:
int Grossrevenue = Convert.ToInt32(GridView1.Columns[5]);

This retrieves the DataField object, which isn't going to do much for you.  Is the Gross Revenue stored in each row?  If so, try something like:
int Grossrevenue = Convert.ToInt32(row.Cells[5].Text);

I'm not sure how you're displaying the Gross Revenue... you might be able to access it via the "row.DataItem" property.... row.DataItem("GrossRevenue")

For #2 you'll probably use the RowUpdating event and the GridViewUpdateEventArgs.  You can access Label1 in that event by:
int NewValue = (int)GridView1.Rows[e.RowIndex].FindControl("Label1").Text;

Good luck!
-- Jason
Hi! Jason,
Below is my update code,but it looks like GridViewCommandEventArgs does not contain definition of RowIndex.I am keep getting an error..  int Medical_UNH = (int)GridView1.Rows[e.RowIndex].FindControl("Label1").Text;..



   
 protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

        decimal Medical_UNH = (decimal)GridView1.Rows[e.RowIndex].FindControl("Label1").Text;
        String Supp_contractual_Allowance = e.Keys["Supp_contractual_Allowance"].ToString();
        String Assertions_key = e.Keys["Assertions_key"].ToString();        
       
         string connectionString = ConfigurationManager.ConnectionStrings["Finance_AppsConnectionString2"].ConnectionString;
        System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(connectionString);
        string queryString = "update Revenue_Aggregate_Assertions set Medicial_UNH = @Medical_UNH, Supp_contractual_Allowance = @Supp_contractual_Allowance where Assertions_key = @Assertions_key";
        System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();

        dbCommand.CommandText = queryString;
        dbCommand.Connection = dbConnection;

        System.Data.IDataParameter dbParam_Medical_UNH = new System.Data.SqlClient.SqlParameter();

        dbParam_Medical_UNH.ParameterName = "@Medical_UNH";
        dbParam_Medical_UNH.Value = Medical_UNH;
        dbParam_Medical_UNH.DbType = System.Data.DbType.String;
        dbCommand.Parameters.Add(dbParam_Medical_UNH);

        System.Data.IDataParameter dbParam_Supp_contractual_Allowance = new System.Data.SqlClient.SqlParameter();

        dbParam_Supp_contractual_Allowance.ParameterName = "@Supp_contractual_Allowance";
        dbParam_Supp_contractual_Allowance.Value = Supp_contractual_Allowance;
        dbParam_Supp_contractual_Allowance.DbType = System.Data.DbType.String;
        dbCommand.Parameters.Add(dbParam_Supp_contractual_Allowance);

        System.Data.IDataParameter dbParam_Assertions_key = new System.Data.SqlClient.SqlParameter();

        dbParam_Assertions_key.ParameterName = "@Assertions_key";
        dbParam_Assertions_key.Value = Assertions_key;
        dbParam_Assertions_key.DbType = System.Data.DbType.String;
        dbCommand.Parameters.Add(dbParam_Assertions_key);

     
        int rowsAffected = 0;

        dbConnection.Open();
        try
        {
            rowsAffected = dbCommand.ExecuteNonQuery();
        }
        finally
        {
            dbConnection.Close();
        }
       
    }
ASKER CERTIFIED SOLUTION
Avatar of Jason Scolaro
Jason Scolaro
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, but it doesn't contain the definition of Text...
 decimal Medical_UNH = (decimal)GridView1.Rows[e.RowIndex].FindControl("Label1").Text;

How can I grap the value of Label1 which is calculated field and save into database?