Link to home
Start Free TrialLog in
Avatar of AndyPandy
AndyPandyFlag for United States of America

asked on

Databind works most of time, except when "TRACK" is selected

Hi Experts,

How can I fix Gridview1 to show "CNT" (a counter) after the Button "TRACK" is pressed?

Simply in Gridview1:
1) CNT is incremented when the column URL is selected, showing how many times the URL was clicked.
2) TRACK button  copies the row into a 2nd table that is the data source for GridView2.

It works fine before "TRACK" is pressed,  but not after,  even though the SQl table column "CNT" is being updated.
It just doesn't show the updated value of CNT on the screen.
I thought the following should show the updated grid values:
            SqlDataSource1.DataBind();
            GridView1.DataBind();
But they do not after "TRACK" is pressed.
When the screen is restarted CNT is correct.

 
grid1.JPG
Avatar of AndyPandy
AndyPandy
Flag of United States of America image

ASKER

Here is the code:
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
   
    string gogetit = string.Empty;
    string holdit = string.Empty;
    string regex = string.Empty;

    protected void LinkButton1_Click(object sender, EventArgs e)  // Link, increment counter
    {
        LinkButton lb = (LinkButton)sender;
        string url_temp = lb.Text;
        Response.Redirect(url_temp, false);

        LinkButton lnk = (LinkButton)sender;
        int index = ((GridViewRow)lnk.NamingContainer).RowIndex;

        GridViewRow selectedRow = GridView1.Rows[index];
        TableCell id_number = selectedRow.Cells[0];

        int id_number_int = Convert.ToInt32(id_number.Text);
        string id_text = id_number.Text;

        //INCREMENT THE NUMBER//  
        //connect to the db    
        string strConn = ConfigurationManager.ConnectionStrings["CS1"].ToString();
        SqlConnection con = new SqlConnection(strConn);
        //the command to increment the value in the Number column by 1 in the row we clicked 
        SqlCommand cmd = new SqlCommand("UPDATE gogetit SET cnt = cnt+1 WHERE  id=@id", con);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@id", id_number_int);
        using (con)
        {   //open the connection        
            con.Open();
            //send the query to increment the number   
            cmd.ExecuteNonQuery();
            SqlDataSource1.DataBind();
            GridView1.DataSourceID = "SqlDataSource1";
            GridView1.DataBind();
        }
    }

        
    protected void Gridview1_RowCommand(Object sender, GridViewCommandEventArgs e) // Track Button
    {
        // If multiple ButtonField column fields are used, use the
        // CommandName property to determine which button was clicked.
      
        if (e.CommandName.CompareTo("TrackButton") == 0)
        {
            // Convert the row index stored in the CommandArgument
            // property to an Integer.
            int index = Convert.ToInt32(e.CommandArgument);

            // Retrieve the row that contains the button clicked 
            // by the user from the Rows collection.      
            GridViewRow row = GridView1.Rows[index];

            string temp_id = row.Cells[0].Text;
            string temp_cnt = row.Cells[1].Text;
            string temp_url = ((LinkButton)row.FindControl("LinkButton1")).Text;

            //AppendSQL_track();
            string strConn = ConfigurationManager.ConnectionStrings["CS1"].ToString();
            string strHostName = System.Net.Dns.GetHostName();
            string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
            using (SqlConnection con = new SqlConnection(strConn))
            {
                // 1. Instantiate a new command
                SqlCommand cmd = new SqlCommand(@"INSERT INTO gogetit_track (id2,url,createdate,cnt) Values ("
                   + temp_id
                   + ",'"
                   + temp_url 
                   + "', getdate(),'"
                   + temp_cnt
                   + "' )");

                // 2. Set the Connection property
                cmd.Connection = con;
                // 3. Open connection
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
                try
                {
                    // 4. Call ExecuteNonQuery to send command
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException se)
                {
                    Response.Write("Result: " + se.Message);
                }
                cmd.Dispose();
                con.Close();
                SqlDataSource2.DataBind();
                GridView2.DataBind();
            }
        }
    }
    
    // Override the OnLoad method to set _text to
    // a default value if it is null.
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        if (holdit == null)
            holdit = "Here is some default text.";
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton linkButton = (LinkButton)e.Row.FindControl("LinkButton1");

            if (linkButton != null)
            {
                //linkButton.Attributes.Add("onclick", "window.open(url); return false;");
            }
        }
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>

<body style="height: 337px; width: 960px;">
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
        EmptyDataText="There are no data records to display."
        OnRowCommand="Gridview1_RowCommand" AllowPaging="True" BorderColor="Red" 
        BorderStyle="Double" BorderWidth="5px" Caption="Gridview1 - DataSource1" 
        CaptionAlign="Top" PageSize="4">
        <Columns>
            <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id"
                InsertVisible="False" />
            <asp:BoundField DataField="cnt" HeaderText="CNT" SortExpression="cnt" />
            <asp:TemplateField HeaderText="URL">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" Text='<%# Eval("url")%>' OnClick='LinkButton1_Click'
                        CommandArgument='<%# Eval("id")%>' runat="server"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:ButtonField ButtonType="Button" CommandName="TrackButton" Text="Track">
                <ControlStyle BackColor="#FF6666" BorderColor="Lime" />
            </asp:ButtonField>
        </Columns>
    </asp:GridView>

    <br />
    
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" 
        DataSourceID="SqlDataSource2" AllowPaging="True" BorderColor="Blue" 
        BorderStyle="Double" BorderWidth="5px" Caption="Gridview2 - DataSource2" 
        CaptionAlign="Top" PageSize="4">
        <Columns>
            <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
                SortExpression="id" />
            <asp:BoundField DataField="id2" HeaderText="id2" SortExpression="id2" />
            <asp:BoundField DataField="cnt" HeaderText="CNT" SortExpression="cnt" />
            <asp:BoundField DataField="url" HeaderText="URL" SortExpression="url" />
            <asp:BoundField DataField="createdate" HeaderText="createdate" SortExpression="createdate" />
        </Columns>
    </asp:GridView>

    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:CS1 %>"
        SelectCommand="SELECT [id], [term], [url], [cnt] FROM [gogetit] ORDER BY [createdate] DESC"></asp:SqlDataSource>

    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CS1 %>"
        SelectCommand="SELECT * FROM [gogetit_track] ORDER BY [createdate] DESC"></asp:SqlDataSource>

    </form>
</body>
</html>

Open in new window

Make sure you disable caching on the SQL Datasource.
Hi Strickdd,

I tried EnableCaching= false without luck,  see code.

Is this what you meant.

Any other ideas?  

Thanks
<asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableCaching=false ConnectionString="<%$ ConnectionStrings:CS1 %>"
        SelectCommand="SELECT [id], [term], [url], [cnt] FROM [gogetit] ORDER BY [createdate] DESC"></asp:SqlDataSource>

    <asp:SqlDataSource ID="SqlDataSource2" runat="server" EnableCaching=false ConnectionString="<%$ ConnectionStrings:CS1 %>"
        SelectCommand="SELECT * FROM [gogetit_track] ORDER BY [createdate] DESC"></asp:SqlDataSource>

Open in new window

I don't think it matters, but you should put double quotes around the "false". Also make sure it's not just appending to the gridview by doing a GridView1.Clear() and GridView2.Clear() before their respective databinds.
No joy.

There is no Clear for GridView,  so GridView1.Clear() gives compile error.Compiler Error Message:

CS1061: 'System.Web.UI.WebControls.GridView' does not contain a definition for 'Clear' and no extension method 'Clear' accepting a first argument of type 'System.Web.UI.WebControls.GridView' could be found (are you missing a using directive or an assembly reference?)

EnableCaching="False" does not seem to have any effect.
ASKER CERTIFIED SOLUTION
Avatar of AndyPandy
AndyPandy
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
Response.Redirect(url_temp,false); changing viewstate is the problem.