locked
Command button is not firing RRS feed

  • Question

  • User-218090889 posted

    Hello Friends,

    "He who want to learn would always ask many questions", please permit my so many questions.

    In my application, I have a code that create button dynamically in a GridView bounded, the code is working fine creating the button. then I want to execute command for the button using Row Command, but the button doe not fire.

    below are my codes

    1' Button creation code in DataRowBond:
    public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                PlaceHolder ph = (PlaceHolder)e.Row.FindControl("phGame");
                   Button bt1 = new Button();
                    bt1.Text = "PalsCall";
                    bt1.ID = "GameCall";
                    bt1.CommandName = "GameCall";
                    bt1.EnableViewState = true;
                    ph.Controls.Clear();
                    ph.Controls.Add(bt1);

                    bt1.Click += delegate
                    {

                    };

    2. code to execute the command:
    public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "GameCall")
            {
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                GridViewRow row2 = (GridViewRow)(((TextBox)e.CommandSource).NamingContainer);
                Button bt1 = (Button)row.FindControl("GameCall");
                TextBox PlayerID = (TextBox)row2.FindControl("PlayerId");
                string PlayerId = PlayerID.Text;
                if (bt1 != null)
                {
                  string ID1 = null;
                        string ID2 = null;
                        string ID3 = null;
                        string connetionString = null;
                        SqlConnection con  ;
                        SqlCommand cmd ;
                        string sql = null;
                        SqlDataReader rdr ;

                        connetionString = "Data Source=MyServerName;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
                        sql = "SELECT (Id) FROM Table_A WHERE (ABS(CAST((BINARY_CHECKSUM(Id, NEWID())) as int))% 10) < 4 ";

                         con = new SqlConnection(connetionString);
                        try
                         {
                         con.Open();
                         cmd = new SqlCommand(sql, con);
                         rdr = cmd.ExecuteReader();
                          while (rdr.Read())
                         {
                             ID1 = Convert.ToString(rdr.GetValue(0));
                             ID2 = Convert.ToString(rdr.GetValue(1));
                             ID3 = Convert.ToString(rdr.GetValue(2));
                        
                        }
                          rdr.Close();
                          cmd.Dispose();
                    
                        }
                          finally
                        {
                          con.Close();
                        }

                        string GameCalls = "INSERT INTO [Table_B] (PlayerId,ScID) VALUES('" + PlayerId + "','" + ID1 + "'),('" + PlayerId + "','" + ID2 + "'),('" + PlayerId + "','" + ID3 + "')";
                        dbClass.ConnectDataBaseToInsert(GameCalls);

                        

                        //ph.Controls.Clear();

                        Response.Redirect("~/GamePage.aspx?Id=" + Session["UserId"].ToString());        
                    };
                }

    Please help me check why the button is not firing.
    Thanks.

    Tuesday, October 4, 2016 12:17 PM

Answers

  • User-1716253493 posted

    seem like you want to do like this

    int i = 0;
    while (rdr.Read())
    {
      switch (i)
      {
        case 0:
            ID1 = Convert.ToString(rdr.GetValue(0));
            break;
        case 1:
            ID2 = Convert.ToString(rdr.GetValue(0));
            break;
        case 2:
            ID3 = Convert.ToString(rdr.GetValue(0));
            break;
       }
       i+=1
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 12, 2016 3:01 PM

All replies

  • User-1716253493 posted

    AFAIK, to use commandname in gridview rowcommand event, you dont need click event

    Set commandname property only.

    You can also pass rowindex or id or playerid or other value by setting commandargument property if you want

    You can get this value from e.commandargument

    Ensure, you don't call gridview1.databind() in every postback

    remove below

                    bt1.Click += delegate
                    {
    
                    };

    Tuesday, October 4, 2016 2:11 PM
  • User-218090889 posted

    Hi oned_gk

    I have removed the

     bt1.Click += delegate
                    {
    
                    };

    I set page Load to  if (!Page.IsPostBack)
    yet it could not fire
    Thursday, October 6, 2016 8:56 AM
  • User-1716253493 posted

    Hi Enzyme,

    CommandSource is the button, not the textboxt

    Try modify this

    Button bt1 = (Button)e.CommandSource; //get the button
    GridViewRow row = (GridViewRow)bt1.NamingContainer; //get the row
    //remove this line GridViewRow row2 = (GridViewRow)(((TextBox)e.CommandSource).NamingContainer);
    TextBox PlayerID = (TextBox)row.FindControl("PlayerId"); //get the textbox

    Thursday, October 6, 2016 5:12 PM
  • User-218090889 posted

    Please don,t be offended Sir, can you give me a sample code on how to get the button, get the row from the button, and get the textbox from the row.

    Thursday, October 6, 2016 6:21 PM
  • User-1716253493 posted

    Replace your code (4 lines) with mine. I just explain the codes.

    I have modify the post

    Friday, October 7, 2016 12:54 AM
  • User-218090889 posted

    Ok,thank, I will try it

    Friday, October 7, 2016 7:41 AM
  • User-218090889 posted

    Hello oned_gk

    I have modified my code with the ones you sent to me, but it would not work as expected.

    below is my recent code

    1. Button creation code in DataRowBond:
    public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                PlaceHolder ph = (PlaceHolder)e.Row.FindControl("phGame");
                   Button bt1 = new Button();
                    bt1.Text = "PalsCall";
                    bt1.ID = "GameCall";
                    bt1.CommandName = "GameCall";
                    bt1.EnableViewState = true;
                    ph.Controls.Clear();
                    ph.Controls.Add(bt1);

    2. code to execute the command:
    public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "GameCall")
            {
             

    Button bt1 = (Button)e.CommandSource; //get the button

    GridViewRow row = (GridViewRow)bt1.NamingContainer; //get the row

    TextBox PlayerID = (TextBox)row.FindControl("PlayerId"); //get the textbox


                string PlayerId = PlayerID.Text;
                if (bt1 != null)
                {
                  string ID1 = null;
                        string ID2 = null;
                        string ID3 = null;
                        string connetionString = null;
                        SqlConnection con  ;
                        SqlCommand cmd ;
                        string sql = null;
                        SqlDataReader rdr ;

                        connetionString = "Data Source=MyServerName;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
                        sql = "SELECT (Id) FROM Table_A WHERE (ABS(CAST((BINARY_CHECKSUM(Id, NEWID())) as int))% 10) < 4 ";

                         con = new SqlConnection(connetionString);
                        try
                         {
                         con.Open();
                         cmd = new SqlCommand(sql, con);
                         rdr = cmd.ExecuteReader();
                          while (rdr.Read())
                         {
                             ID1 = Convert.ToString(rdr.GetValue(0));
                             ID2 = Convert.ToString(rdr.GetValue(1));
                             ID3 = Convert.ToString(rdr.GetValue(2));
                        
                        }
                          rdr.Close();
                          cmd.Dispose();
                    
                        }
                          finally
                        {
                          con.Close();
                        }

                        string GameCalls = "INSERT INTO [Table_B] (PlayerId,ScID) VALUES('" + PlayerId + "','" + ID1 + "'),('" + PlayerId + "','" + ID2 + "'),('" + PlayerId + "','" + ID3 + "')";
                        dbClass.ConnectDataBaseToInsert(GameCalls);

                        

                        //ph.Controls.Clear();

                        Response.Redirect("~/GamePage.aspx?Id=" + Session["UserId"].ToString());        
                    };
                }

    3. the asp mark up of my GridView:

    <asp:GridView ID="GridView1" runat="server"
        CellPadding="4" EnableModelValidation="True"
        GridLines="None" Height="123px"
        OnRowDataBound="GridView1_RowDataBound"
         OnRowCommand="GridView1_RowCommand"
                        

        style="margin-right: 0px" ForeColor="#333333" AutoGenerateColumns="False"
        Font-Bold="False" Font-Size="Small" Width="522px"
                        OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                         
        <AlternatingRowStyle BackColor="White" />
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" style="color: #008000"></asp:Label>
                   
                    <br />
                    <span class="auto-style1" style="color: #000066">Lot ID:.</span><asp:TextBox ID="PlayerId" runat="server" style="height: 19px; width: 152px"
                        BorderColor="#3366CC" BorderStyle="Groove"
                        ReadOnly='True'
                        Text='<%# DataBinder.Eval(Container.DataItem,"PlayerId") %>'
                        OnTextChanged="TextBoxPlayerId_TextChanged" Height="19px" Width="152px"></asp:TextBox>
                     
                    
                    <asp:PlaceHolder ID="phGame" runat="server"></asp:PlaceHolder>
                    <br />
                                    
                    
                </ItemTemplate>
            </asp:TemplateField>

    Please check what is wrong I am getting worried about this point that is not working yet.

    Monday, October 10, 2016 6:08 AM
  • User-1716253493 posted

    There are several lines i don't understand, not realy understand the scenario.

    sql = "SELECT (Id) FROM Table_A WHERE (ABS(CAST((BINARY_CHECKSUM(Id, NEWID())) as int))% 10) < 4 ";

    the query results above is one column id

    while (rdr.Read())
    {
        ID1 = Convert.ToString(rdr.GetValue(0));
        ID2 = Convert.ToString(rdr.GetValue(1));
        ID3 = Convert.ToString(rdr.GetValue(2));
    }

    but you read the data from 3 columns, this causes an error. But because it inside try-catch, you can't see the message.

    Response.Redirect("~/GamePage.aspx?Id=" + Session["UserId"].ToString());       

    the code will redirect you to the page with querystring id, but actualy you have session value that you can read from the page.

    So, i think you don't need id querystring.

    Monday, October 10, 2016 6:42 AM
  • User-218090889 posted

    My idea here is to randomly select three IDs from Id column in Table_A using 
    sql = "SELECT (Id) FROM Table_A WHERE (ABS(CAST((BINARY_CHECKSUM(Id, NEWID())) as int))% 10) < 4 ";  
    and read the values with ExecuteReader to get them as variables to be used to insert into Table_B

    then to still remain on the page "Game page" with the UserId,
    that why i try to re-direct to
    Response.Redirect("~/GamePage.aspx?Id=" + Session["UserId"].ToString());

    Tried executing
    SELECT (Id) FROM Table_A WHERE (ABS(CAST((BINARY_CHECKSUM(Id, NEWID())) as int))% 10) < 4
    in SQL query of MS SQL Server Management Studio  and it randomly selects from the Id column, work well.

    Monday, October 10, 2016 12:19 PM
  • User-1716253493 posted

    seem like you want to do like this

    int i = 0;
    while (rdr.Read())
    {
      switch (i)
      {
        case 0:
            ID1 = Convert.ToString(rdr.GetValue(0));
            break;
        case 1:
            ID2 = Convert.ToString(rdr.GetValue(0));
            break;
        case 2:
            ID3 = Convert.ToString(rdr.GetValue(0));
            break;
       }
       i+=1
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 12, 2016 3:01 PM
  • User-218090889 posted

    Hi oned_gk

    thanks for your contribution, i think this is what i need to do.

    Sunday, October 16, 2016 6:45 PM
  • User-218090889 posted

    I have in my GridView some dynamic created buttons inside custom template. When I click on any of the buttons the entire button in the GridView disappears and the page will not fire. I guess all the dynamic created buttons are losing view state on postback.


    Please how do I put my code to have the buttons maintain View state and get fired?

    Below is some of my codes ( item 1 and 2 below are working very well)

    1)      The page load.
    protected void Page_Load(object sender, EventArgs e)

        {

                    if (!Page.IsPostBack)

            {

                if (!object.Equals(Session["UserId"], null))
                 {

                    //**my connection and sql query here;

                    if (dt.Rows.Count > 0)

                    {

                        GridView1.DataSource = dt;

                        GridView1.DataBind();

     

                    }

                }

            }

     

    2)      GridView Rowdatabond
    public void GridViewUserLots_RowDataBound(object sender, GridViewRowEventArgs e)

        {

            if (e.Row.RowType == DataControlRowType.DataRow)

            {

                PlaceHolder ph = (PlaceHolder)e.Row.FindControl("ph1");
                    Button bt1 = new Button();

                    bt1.ID = "GameCall" ;

                    bt1.Text = "Game Call";

                    bt1.CommandName = "GameCall";

                    bt1.EnableViewState = true;

                    ph.Controls.Clear();

                    ph.Controls.Add(bt1);

                                  

                }

     

    3)      GridView RowCommand
        public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

        {

              if (e.CommandName == "GameCall")

               {

                    Button bt1 = (Button)e.CommandSource;

                    GridViewRow row = (GridViewRow)bt1.NamingContainer;

                    Label CallNote = (Label)row.FindControl("Label1");

                    TextBox PlayerID = (TextBox)row.FindControl("PlayerId");

                    string PlayerId = PlayerID.Text;

     

                    if (bt1 != null)

                    {

                        string ID1 = null;

                        string ID2 = null;

                        string ID3 = null;

                        string connetionString = null;

                        SqlConnection con;

                        SqlCommand cmdd;

                        string sql = null;

                        SqlDataReader rdr;

     

     

                        connetionString = "Data Source=Myserver;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";

                        sql = "SELECT (Id) FROM Table_A WHERE (ABS(CAST((BINARY_CHECKSUM(Id, NEWID())) as int))% 100) < 8 ";

     

                        con = new SqlConnection(connetionString);

                        try

                        {

                            con.Open();

                            cmdd = new SqlCommand(sql, con);

                            rdr = cmdd.ExecuteReader();

                           int i = 0;

                           while (rdr.Read())

                          {

                          switch (i)

                          {

                          case 0:

                          ID1 = Convert.ToString(rdr.GetValue(0));

                          break;

                          case 1:

                          ID2 = Convert.ToString(rdr.GetValue(0));

                          break;

                          case 2:

                          ID3 = Convert.ToString(rdr.GetValue(0));

                          break;

                          }

                          i += 1;

                          }

                            rdr.Close();

                            cmdd.Dispose();

     

                        }

                        finally

                        {

                            con.Close();

                        }

     

                        string GameCalls = "INSERT INTO [Table_B] (PlayerId,ScID) VALUES('" + PlayerId + "','" + ID1 + "'),('" + PlayerId + "','" + ID2 + "'),('" + PlayerId + "','" + ID3 + "')";
                        dbClass.ConnectDataBaseToInsert(GameCalls);

                        
    }                    CallNote.Text = "Game Call has been sent";
                        //ph.Controls.Clear();

                        Response.Redirect("~/GamePage.aspx?Id=" + Session["UserId"].ToString());        
                    };
               

     



     

    Sunday, October 16, 2016 7:01 PM