0

Hi I have a GridView control and in it a TextBox control inside an EditItemTemplate Field.
Now I need to change the textbox text when the user enters the edit mode.
When I run the program the textbox will take the value of the label that was in the ItemTemplate and I cant access the textbox.
.aspx:

<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel" 
onrowupdating="GridView1_RowUpdating" onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound" DataKeyNames="TweetID">
<Columns>
<asp:TemplateField HeaderText="ProfilePicture">
<ItemTemplate>
<asp:ImageButton ID="ProfileImage" runat="server" CommandName="Redirect" 
CommandArgument='<%# Container.DataItemIndex %>' Height="40px" Width="40px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FullName">
<ItemTemplate>
<asp:label ID="FullNameLabel" runat="server" text='<%#Eval("FullName") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="UserNameLabel" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<%--<asp:Label ID="TweetLabel" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>--%>
<asp:Label ID="TweetLabel" runat="server" Text=""></asp:Label>
</ItemTemplate>

<EditItemTemplate>
<asp:TextBox ID="TweetTB" runat="server" Text='<%#Eval("TweetText") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="TweetPic" runat="server" 
ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' Height="125px" Width="222px" />
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:ImageButton ID="ReTweetImgBTN" runat="server" 
ImageUrl="~/SrcImage/retweet-action.png" Height="27px" Width="29px" 
CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Label ID="ReTweetEd" runat="server" Text="ReTweetEd" Visible="false"></asp:Label>--%>
 <%--<asp:Button ID="ReTweetBTN" runat="server" Text="ReTweet"  CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />--%>
 <asp:Label ID="ReTweetStat" runat="server" Visible="false"></asp:Label>  
 </ItemTemplate>
 </asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
 <asp:ImageButton ID="LikeImgBTN" runat="server" ImageUrl="~/SrcImage/like-action.png"
 Height="27px" Width="29px" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>'/>
 <%--<asp:Button ID="LikeBTN" runat="server" Text="Like"  CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />--%>
 <asp:Label ID="LikeStat" runat="server" Visible="false"></asp:Label>
  </ItemTemplate>
 </asp:TemplateField>

 <asp:TemplateField HeaderText="Options">  
 <ItemTemplate>  
 <asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit"  />
 </ItemTemplate>  
 <EditItemTemplate>  
 <asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
 <asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
 <asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>  
 </EditItemTemplate>  
 </asp:TemplateField>
 <asp:TemplateField HeaderText="TweetID" Visible="false">
 <ItemTemplate>
 <asp:HiddenField ID="TweetID" runat="server" Value='<%#Eval("TweetID") %>'  />
 </ItemTemplate>
 </asp:TemplateField>

 <asp:TemplateField HeaderText="UserID" Visible="false">
 <ItemTemplate>
 <asp:HiddenField ID="UserID" runat="server" Value='<%#Eval("UserID") %>'/>
 </ItemTemplate>
 </asp:TemplateField>

 </Columns>
 </asp:GridView>

.cs:

protected void Page_Load(object sender, EventArgs e)
    {
        Session["UserID"] = 1; // To be removed
        if(!IsPostBack)
            BindGridview();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int userId = int.Parse(Session["UserID"].ToString());
        if (e.CommandName == "Like")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
            {
                int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
                int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
                LikeHelper.Like(tweetID, userId);
            }
            else
                LikeHelper.Like(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
        }
        if (e.CommandName == "ReTweet")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
            {
                int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
                int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
                ReTweetHelper.ReTweet(tweetID, userId);
            }
            else
                ReTweetHelper.ReTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
        }
        if (e.CommandName == "UnReTweet")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int RetweetID = ReTweetHelper.GetReTweetIdFromReTweetByUserIdAndTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
            int TweetID = NewTweetHelper.GetTweetIdFromTweetByReTweetId(RetweetID);
            ReTweetHelper.RemoveReTweet(RetweetID);
            NewTweetHelper.GeneralRemoveTweet(TweetID);
        }
        if (e.CommandName == "Redirect")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int TweetID = int.Parse(GridView1.DataKeys[index].Value.ToString());
            if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(TweetID))
            {
                int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(TweetID);
                int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
                int UserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
                Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(UserID));
            }
            else
                Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(NewTweetHelper.GetUserIdFromTweetByTweetId(TweetID)));
        }
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GridView1.DataBind();
        //TextBox TextBox = GridView1.Rows[e.NewEditIndex].FindControl("TweetTB") as TextBox;
        //HiddenField TweetID = GridView1.Rows[e.NewEditIndex].FindControl("TweetID") as HiddenField;
        //TextBox.Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(TweetID.Value.ToString())).TweetText;
    }
    protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridView1.DataBind();
    }
    public void BindGridview()
    {
        int userId = int.Parse(Session["UserID"].ToString());
        ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
        DataSet ds = objWs.SelectTweets(userId, 0);
        DataTable dt = ds.Tables[0];
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int userId = int.Parse(Session["UserID"].ToString());
        int index = Convert.ToInt32(e.RowIndex);
        if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
        {
            int RetweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
            ReTweetHelper.RemoveReTweet(RetweetID);
            NewTweetHelper.GeneralRemoveTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()));
        }
        else
            NewTweetHelper.GeneralRemoveTweet(Convert.ToInt32(GridView1.DataKeys[index].Value.ToString()));
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        int userId = int.Parse(Session["UserID"].ToString());
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HiddenField userIdLbl = (HiddenField)e.Row.FindControl("UserID");
            HiddenField tweetid = (HiddenField)e.Row.FindControl("TweetID");

            LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
            editBt.Visible = userId == Convert.ToInt32(userIdLbl.Value);

            ImageButton ProfileImage = e.Row.FindControl("ProfileImage") as ImageButton;
            ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(int.Parse(userIdLbl.Value.ToString()));

            // if retweet
            if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
            {
                Tweet tweet = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
                string FullName = UserHelper.GetName(tweet.UserID);
                // change tweet
                Label name = e.Row.FindControl("FullNameLabel") as Label;
                Label UserName = e.Row.FindControl("UserNameLabel") as Label;
                int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
                int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
                int RealUserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
                name.Text = "Retweeted by " + FullName + "<br>" + UserHelper.GetName(RealUserID);
                UserName.Text = UserHelper.GetUserName(RealUserID);
                ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(RealUserID);
                editBt.Visible = false;
            }

            //if there is image
            Image img = (Image)e.Row.FindControl("TweetPic");
            img.Visible = img.ImageUrl != "~/UploadedImages/";

            //stats
            Label LikeStat = e.Row.FindControl("LikeStat") as Label;
            Label ReTweetStat = e.Row.FindControl("ReTweetStat") as Label;
            if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
            {
                int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
                int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
                LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(RealTweetID).ToString();
                if (int.Parse(LikeStat.Text.ToString()) > 0)
                    LikeStat.Visible = true;
                ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(RealTweetID).ToString();
                if (int.Parse(ReTweetStat.Text.ToString()) > 0)
                    ReTweetStat.Visible = true;
            }
            else
            {
                LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(int.Parse(tweetid.Value.ToString())).ToString();
                if (int.Parse(LikeStat.Text.ToString()) > 0)
                    LikeStat.Visible = true;
                ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(int.Parse(tweetid.Value.ToString())).ToString();
                if (int.Parse(ReTweetStat.Text.ToString()) > 0)
                    ReTweetStat.Visible = true;
            }

            // retweeted
            if (ReTweetHelper.IsReTweetExistByUserIdAndTweetId(userId,int.Parse(tweetid.Value.ToString())))
            {
                ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
                Retweet.ImageUrl = "~/SrcImage/retweet-action-on.png";
                Retweet.CommandName = "UnReTweet";
            }
            if (NewTweetHelper.IsTweetByUser(int.Parse(tweetid.Value.ToString()), userId)) 
            {
                ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
                Retweet.ImageUrl = "~/SrcImage/retweet-action-inactive.png";
                Retweet.CommandName = null;
            }

            //Like Button
            ImageButton LikeImg = e.Row.FindControl("LikeImgBTN") as ImageButton;
            if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
            {
                int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
                int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
                if(LikeHelper.IsUserLikeTweet(userId,RealTweetID))    
                    LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
            }
            else
            {
                if (LikeHelper.IsUserLikeTweet(userId,int.Parse(tweetid.Value.ToString())))
                    LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";

            }

            //Hyper Link Text

            Label TweetLabel = (Label)e.Row.FindControl("TweetLabel");
            //TextBox TweetTB = (TextBox)e.Row.FindControl("TweetTB");
            Tweet TweetText = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
            //TweetTB.Text = "a";// TweetText.TweetText.ToString();
            string text = NewTweetHelper.HyperLinkTweet(int.Parse(tweetid.Value.ToString()));
            //TweetText.TweetText= text; //need?
            TweetLabel.Text = text;

            //Change Tb in edit cand do it in RowEditting
            //if (e.Row.RowState == DataControlRowState.Edit)
            //{
            //    TextBox TextBox = e.Row.FindControl("TweetTB") as TextBox;
            //    Tweet Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
            //    TextBox.Text = "abc";
            //}

        }
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        HiddenField TweetID = GridView1.Rows[e.RowIndex].FindControl("TweetID") as HiddenField;
        TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("TweetTB") as TextBox;
        NewTweetHelper.UpdateTweet(int.Parse(TweetID.Value), TweetText.Text);
        GridView1.EditIndex = -1;
        BindGridview();
    }
Rokni
  • 67
  • 13

1 Answers1

1

In the RowEditing event, you can set the EditIndex value and re-bind the data to the GridView:

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindGridView();
}

protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    BindGridView();
}

Then, in the RowDataBound event, you can access the controls of the row:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex == GridView1.EditIndex)
    {
        TextBox txtBox = e.Row.FindControl("TweetTB") as TextBox;
        ...
    }
    else
    {
        ...
    }
}
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • It dosnt work when i do that it reloads the page but not the gridview – Rokni Jun 02 '16 at 18:29
  • How do you set the data source? – ConnorsFan Jun 02 '16 at 18:34
  • I use a DataTable as the data source. – Rokni Jun 02 '16 at 18:35
  • Where do you set it? If you set it in code-behind, you must do it again in the `RowEditing` event, after setting the `EditIndex`. And if you already set it in `Page_Load`, it should be inside an `if (!IsPostBack)` condition. See my answer in this post: http://stackoverflow.com/questions/36827111/asp-net-gridview-how-to-edit-and-delete-data-records/36828018#36828018. – ConnorsFan Jun 02 '16 at 18:38
  • Well i all ready did all of that but just not databind in the row editing because when i do that the page refreshs but the gridview dosnt load – Rokni Jun 02 '16 at 18:51
  • I would have to see how (and where) you set the data source to understand what is going on. – ConnorsFan Jun 02 '16 at 19:03
  • I saw your updated question and modified my answer to include your `BindGridView` function. – ConnorsFan Jun 02 '16 at 20:14
  • I cant use it il get other errors because of my databound – Rokni Jun 02 '16 at 20:46
  • In `RowDataBound`, you may have to check if some controls exist or not. For example, `TweetLabel` is present in "normal" rows but is not present in the edited row. So you have to check if the control is null before using it, or put some of the code in the condition shown in my `RowDataBound` example above. – ConnorsFan Jun 02 '16 at 21:01
  • Sorry left it for a week but i had 4 tests this week so only now i have time for the project. I cant manage to do what you said, but i still cant understand if a label and textbox get the same text from a database and in the label i manipulate the text why will the textbox keep the manipulated text? – Rokni Jun 09 '16 at 18:12
  • well i took your suggestion and changed it a little but it worked. – Rokni Jun 10 '16 at 11:40