I've got a gridview, which each row have a edit and a delete button.
I've managed to put my edit button working, but not the delete button.
Here's my aspx:
<asp:GridView ID="gvfaq" runat="server" AutoGenerateColumns="false" DataKeyNames="faq_id" OnRowDataBound="gvfaq_RowDataBound" OnRowCommand="gvfaq_RowCommand" OnRowDeleting="gvfaq_RowDeleting" >
<Columns>
<asp:BoundField ItemStyle-Width="100px" DataField="text" HeaderText="Text" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button runat="server" ID="editbutton" CommandArgument='<%# Eval("faq_id") %>' CommandName="Edit" Text="Edit" />
<asp:Button runat="server" ID="delbutton" CommandArgument='<%# Eval("faq_id") %>' CommandName="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And this is my code behind:
protected void gvfaq_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int ID = Convert.ToInt32(e.CommandArgument);
DeleteFAQ(ID);
}
}
protected void gvfaq_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button l1 = (Button)e.Row.FindControl("editbutton");
l1.Attributes.Add("onclick", "Javascript:suport(" + l1.CommandArgument.ToString() + ");return false;");
l1.Attributes.Add("onClientClick", "Javascript:suport(" + l1.CommandArgument.ToString() + ");return false;");
Button l2 = (Button)e.Row.FindControl("delbutton");
l2.Attributes.Add("onclick", "javascript:return confirm('Are you sure you want to delete this record?')");
l2.Attributes.Add("onClientClick", "javascript:return confirm('Are you sure you want to delete this record?')");
}
}
protected void gvfaq_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView gv = (GridView)this.FindControl("gvfaq");
int ID = (int)gv.DataKeys[e.RowIndex].Value;
DeleteFAQ(ID);
}
protected void DeleteFAQ(int ID)
{
using (SqlCommand myCommand = new SqlCommand())
using (SqlConnection myServerCreate = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ServerCreate"].ConnectionString))
{
myServerCreate.Open();
myCommand.Connection = myServerCreate;
myCommand.CommandText = "delete from faq where faq_id = " + ID;
myCommand.ExecuteNonQuery();
}
ScriptManager.RegisterStartupScript(Page, typeof(Page), "Close", "__doPostBack('','Delete');", true);
}
The strange, is that I have another page, from where I copied/rearragend this code, and there is working fine.
Thanks.
UPDATE
If I check the html generated on the other page button, this code is added, which doesn't succeed in this:
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$gvDocuments$ctl02$delbutton", "", true, "", "", false, false))
Related
I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
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();
}
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
{
...
}
}
I have created gridview with paging and search a data within gridview.I have number of data and number of page if u filter data in gridview it successfully display result with paging. After display i will click on next page because gridview will display only 10 records per page but i have more than 10 records which i have filtered so it will display page wise. Then when i click next page gridview will loads whole data from database and display but i want display only filtered record while searching data.
the aspx code is below
<asp:Button ID="Search" Text="Search" runat="server" CssClass="searchbtn" OnClick="Search_Click" />
<asp:GridView ID="gvEdit" runat="server" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="10" OnRowCommand="gvEdit_RowCommand">
<HeaderStyle HorizontalAlign="Center" BackColor="#2D96CE" ForeColor="White" />
<AlternatingRowStyle BackColor="#D4EFFD" />
<PagerSettings Position="Top" />
<PagerStyle Height="8px" HorizontalAlign="Center" />
<PagerTemplate>
<table align="center" style="width: 100%;" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="center" style="width: 60%;">
<table align="center" width="50%">
<tr>
<td>
<asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
</td>
<td style=" width: 8%;">
<asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
<asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="200px" />
<asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="11%" />
<asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-Width="19%" />
<asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-Width="13%" />
<asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-Width="200px" />
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="" HeaderText="Schedule1" ItemStyle-Width="6.9%">
<ItemTemplate>
<a href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
<img src="<%#Eval("schedule1") %>" alt="" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Copy">
<ItemTemplate>
<asp:ImageButton ID="lnkDuplicate" runat="server"
ImageUrl="~/Images/grid/file_duplicate 35x35.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Edit" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="lnkBtnContinue" runat="server"
ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDel" runat="server"
ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and aspx.cs code is below
protected void Search_Click(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
try
{
if (txtsearch.Text != "")
{
if (ViewState["data"] != null)
{
DataTable dt = (DataTable)ViewState["data"];
DataView dv = new DataView(dt);
dv.RowFilter = "ref_no Like '%" + txtsearch.Text + "%' OR fum Like '%" + txtsearch.Text + "%' OR filing_type Like '%" + txtsearch.Text + "%'OR business_name Like '%" + txtsearch.Text + "%'OR filing_status Like '%" + txtsearch.Text + "%'";
ViewState["filter"] = dv;
gvEdit.DataSource = dv;
gvEdit.DataBind();
//gvformlist.DataSource = dv;
//gvformlist.DataBind();
}
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
protected void Reset_Click(object sender, EventArgs e)
{
txtsearch.Text = "";
gvEdit.DataSource = ViewState["data"];
gvEdit.DataBind();
//gvformlist.DataSource = ViewState["data"];
//gvformlist.DataBind();
}
protected void gvformlist_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//gvEdit.PageIndex = e.NewPageIndex;
//gvformlist.PageIndex = e.NewPageIndex;
LoadFormList();
}
protected void gvformlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow pagerRow = gvEdit.TopPagerRow;
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (e.Row.RowType == DataControlRowType.Pager)
{
pageLabel.Text = "Page " + (gvEdit.PageIndex + 1) + " of " + gvEdit.PageCount;
}
}
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, string DDlPager)
{
// to Get No of pages and Page Navigation
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
ImageButton btnFirst = (ImageButton)gvPagerRow.FindControl("ImgeBtnFirst");
ImageButton btnPrevious = (ImageButton)gvPagerRow.FindControl("ImgbtnPrevious");
ImageButton btnNext = (ImageButton)gvPagerRow.FindControl("ImgbtnNext");
ImageButton btnLast = (ImageButton)gvPagerRow.FindControl("ImgbtnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DDlPager);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
string strPgeIndx = Convert.ToString(gridView.PageIndex + 1) + " of "
+ gridView.PageCount.ToString();
Label lblpageindx = (Label)gvPagerRow.FindControl("lblpageindx");
lblpageindx.Text += strPgeIndx;
}
protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
{
gvEdit.PageIndex = ((DropDownList)sender).SelectedIndex;
LoadFormList();
}
protected void gvEdit_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(gvEdit, e.Row, this, "ddlPageSelector");
}
}
protected void gvEdit_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
I have changed code in gvEdit_PageIndexChanging as per someone suggestion code is below
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (ViewState["filter"] != null)
{
gvEdit.PageIndex = e.NewPageIndex;
gvEdit.DataSource = ViewState["filter"];
gvEdit.DataBind();
}
else
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
after that i run the code and i am getting error
error is System.Runtime.Serialization.SerializationException: Type 'System.Data.DataView' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
According to your question I try to give an answer. If you find my answer useful then mark is as answer or vote it up.
What I have done in below code is when user click on search button without input any student name it shows per page 10 records of all students and if you search by name it shows only specific students with paging. In below code I use a stored procedure and in that I put three parameters such as following:
#startRowIndex int
#pageSize int
#studentname varchar(50) = NULL
Default.aspx markup:
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<tr>
<td>Gridview Pagging</td>
</tr>
<tr>
<td>
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div>
<asp:GridView ID="gv" runat="server" Width="100%" EmptyDataText="No Data Found!"
ShowFooter="False" AutoGenerateColumns="False" SkinID="WithOutPaging" GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="Studentname" HeaderText="Student Names"></asp:BoundField>
<asp:BoundField DataField="Studentage" HeaderText="Age"></asp:BoundField>
</Columns>
<EmptyDataRowStyle CssClass="emptyrow" />
<HeaderStyle CssClass="headerstyle2" />
<FooterStyle CssClass="footerstyle"></FooterStyle>
<EditRowStyle CssClass="editrowstyle"></EditRowStyle>
<SelectedRowStyle CssClass="selectedrowstyle"></SelectedRowStyle>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></PagerStyle>
</asp:GridView>
</div>
<div style="margin-top: 20px; margin-bottom: 70px;" align="center">
<asp:Button ID="btnFirst" runat="server" Text="First" CommandName="First" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnPrevious" runat="server" Text="Previous" CommandName="Previous"
OnCommand="ChangePage" Visible="False" />
<asp:Button ID="btnNext" runat="server" Text="Next" CommandName="Next" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnLast" runat="server" Text="Last" CommandName="Last" OnCommand="ChangePage"
Visible="False" />
<br />
<br />
<asp:Label ID="lblPageText1" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> Page </asp:Label>
<asp:Label ID="lblCurrentPage" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
<asp:Label ID="lblPageText2" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> of </asp:Label>
<asp:Label ID="lbltotalPages" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Default.aspx.cs code:
#region "Declaration"
private int pageSize = 10;
SqlConnection con;
string conquery = "Data Source=.;Initial Catalog=GridviewPagging;User ID=sa;Password = 123";
#endregion
#region "Events"
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["startRowIndex"] = 0;
ViewState["currentPageNumber"] = 0;
}
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
ViewState["currentPageNumber"] = 1;
ViewState["startRowIndex"] = 0;
break;
case "Previous":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) - 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) - pageSize;
break;
case "Next":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) + 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) + pageSize;
break;
case "Last":
ViewState["startRowIndex"] = pageSize * (Int32.Parse(lbltotalPages.Text) - 1);
ViewState["currentPageNumber"] = lbltotalPages.Text;
break;
}
this.fillgridview();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
fillgridview();
}
#endregion
#region "Methods"
private DataSet ds(int RowIndex, int Pagesize, string studentname)
{
DataSet dataset;
try
{
con = new SqlConnection(conquery);
SqlCommand cmd = new SqlCommand("SP_GET_STUDENT_DATA", con);
cmd.Parameters.AddWithValue("#startRowIndex", RowIndex);
cmd.Parameters.AddWithValue("#pageSize", Pagesize);
cmd.Parameters.AddWithValue("#studentname", studentname);
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
dataset = new DataSet();
da.Fill(dataset);
}
return dataset;
}
catch (SqlException ex)
{
return dataset = null;
}
}
private void fillgridview()
{
DataSet newds = ds(Convert.ToInt32(ViewState["startRowIndex"].ToString()), pageSize, searchbox.Text.Trim());
if (newds.Tables.Count == 0)
{
return;
}
else
{
btnFirst.Visible = true;
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
lblCurrentPage.Visible = true;
lbltotalPages.Visible = true;
lblPageText1.Visible = true;
lblPageText2.Visible = true;
ViewState["TotalRows"] = newds.Tables[1].Rows[0][0];
newds.Tables[1].Rows.Clear();
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 0)
{
ViewState["currentPageNumber"] = 1;
}
setPages();
this.gv.Visible = true;
this.gv.DataSource = newds.Tables[0];
this.gv.DataBind();
}
}
private void setPages()
{
lbltotalPages.Text = "";
lblCurrentPage.Text = "";
try
{
lbltotalPages.Text = CalculateTotalPages(Convert.ToDouble(ViewState["TotalRows"])).ToString();
lblCurrentPage.Text = (ViewState["currentPageNumber"] == null ? "0" : ViewState["currentPageNumber"].ToString());
if (Int32.Parse(lblCurrentPage.Text) == 0 | Int32.Parse(lbltotalPages.Text) == 0)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
else
{
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 1)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
if (int.Parse(lbltotalPages.Text) > 0)
{
this.btnNext.Enabled = true;
this.btnLast.Enabled = true;
}
else
{
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
}
if (Convert.ToInt32(ViewState["currentPageNumber"]) == int.Parse(lbltotalPages.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
}
catch (Exception ex)
{
}
}
private int CalculateTotalPages(double totalrows)
{
return Convert.ToInt32(Math.Ceiling(totalrows / pageSize));
}
#endregion
first set enablepagingandcallback = false in gridview , then add
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1; //it is the datasource with filtered query which does the work
GridView1.DataBind();
}
I have created this gridview .This is my code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
here's my html gridview code
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" Font-Bold="True" Font-Italic="False" Font-Size="Small" Height="72px" style="margin-left: 41px; margin-top: 108px" Width="783px" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="OnRowDataBound">
<AlternatingRowStyle BackColor="#FFFFCC" BorderColor="#FF9900" Wrap="False" />
<Columns>
<asp:TemplateField HeaderText="TASK ID" SortExpression="TASK ID" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="TASKID" runat="server" Text='<%#Eval("[TASK ID]") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NATURE OF PAYMENT" SortExpression="NATURE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="NOP" runat="server" Text='<%#Eval("[NATURE OF PAYMENT]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownnop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DESC" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DESC" Text='<%#Eval("[DESC]") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID ="DESC" runat="server" Text='<%#Eval("[DESC]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="REQUIREDFIELDVALIDATORDESC" runat="server" ControlToValidate="DESC" ErrorMessage="FIELD CANNOT BE EMPTY"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FREQUENCY" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="FREQUENCY" Text='<%#Eval("FREQUENCY") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownfreq"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOP" Text='<%#Eval("PREALERT1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF SUBMISSION OF RETURN" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOSOR" Text='<%#Eval("PREALERT2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddosor"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="OWNER" Text='<%#Eval("OWNER") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownowner"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VERIFICATION OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="VO" Text='<%#Eval("[VERIFICATION OWNER]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownvo"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="STATUS" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="STATUS" Text='<%#Eval("STATUS") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat ="server" ID="dropdownstatus">
<asp:ListItem Text="Active" Value="1"></asp:ListItem>
<asp:ListItem Text="Inactive" Value="0"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false" HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="ID" Text='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="4" />
</asp:GridView>
So, my problem here is that Iam able to edit is using the edit events but I am not able to
populate the dropdown inside the gridview, whereas Iam able to do the same outside the GridView.
Here's my full codebehind
{
Comp obj6 = new Comp();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate gridview
TextBox2.Focus();
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
{
// populate dropdownlist for prealert 1
for (int i = 0; i <= 30; i++)
{
DropDownList3.Items.Insert(i, new ListItem((i + 1).ToString(), (i + 1).ToString()));
}
DropDownList3.DataBind();
}
{
// populate dropdown list for prealert 2
for (int j = 0; j <= 30; j++)
{
DropDownList4.Items.Insert(j, new ListItem((j + 1).ToString(), (j + 1).ToString()));
}
DropDownList4.DataBind();
}
{
//populate dropdown for Nature of Payment
string query = "select * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';";
string columnname = "DESC";
string datavaluefield = "DESC";
obj6.PopulateCombo(DropDownList1, query, columnname, datavaluefield);
}
{
//populate dropdown for frequency
string query1 = "select * from Compliance_Tracker.dbo.frequencyMaster where STATUS='1';";
string columnname1 = "DESC";
string datavaluefield1 = "DESC";
obj6.PopulateCombo(DropDownList2, query1, columnname1, datavaluefield1);
}
{
//populate dropdown for owner
string query2 = "select * from Compliance_Tracker.dbo.ownerMaster where STATUS='1';";
string columnname2 = "NAME";
string datavaluefield2 = "NAME";
obj6.PopulateCombo(DropDownList5, query2, columnname2, datavaluefield2);
}
{
//populate dropdown for owner verification
string query3 = "select * from Compliance_Tracker.dbo.verificationMaster where STATUS='1'";
string columnname3 = "NAME";
string datavaluefield3 = "NAME";
obj6.PopulateCombo(DropDownList6, query3, columnname3, datavaluefield3);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "insert into Compliance_Tracker.dbo.tasklistManager([NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],STATUS)values('" + DropDownList1.SelectedItem.Text + "','" + TextBox2.Text + "','" + DropDownList2.SelectedItem.Text + "','" + DropDownList3.SelectedItem.Text + "','" + DropDownList4.SelectedItem.Text + "','" + DropDownList5.SelectedItem.Text + "','" + DropDownList6.SelectedItem.Text + "','" + DropDownList7.SelectedValue + "');";
obj6.ExecuteScalar(query);
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
TextBox2.Text = string.Empty;
DropDownList7.SelectedItem.Text = "Active";
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string query = "delete Compliance_Tracker.dbo.tasklistManager where Compliance_Tracker.dbo.tasklistManager.ID = " + ID;
string populatequery = query + ";select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.BindGridData(populatequery, GridView1);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
}
And here's the fetchdata code
public DataTable Fetchdata(string strSQL)
{
SqlDataAdapter DAdpt = new SqlDataAdapter();
DataSet DSet = new DataSet();
try
{
if (Conn.State == ConnectionState.Closed)
Conn.Open();
DAdpt = new SqlDataAdapter(strSQL, Conn);
DAdpt.Fill(DSet);
return DSet.Tables[0];
}
catch (Exception Ex)
{
return null;
throw new Exception(Ex.Message);
}
finally
{
DAdpt.Dispose();
DSet.Dispose();
Conn.Close();
}
}
Must be some problem with find control code. Try the one I have using in the code given below :
protected void GrdPDataEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Replace your find corntrol code with this
DropDownList drpnop = (DropDownList)e.Row.FindControl("dropdownnop");
if (drpnop != null)
{
drpnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
drpnop.DataTextField = "DESC";
drpnop.DataValueField = "DESC";
drpnop.DataBind();
}
}
}
You can't directly access the DropDownList inside of the GridView while the gridview is being generated. What you'll have to do is to use the GridView OnRowCreated event and populate the dropdown that way. I don't have any sample code handy, but there are a ton of references on the internet.
Most of your code is usable, but you'll need to move a few things around.
Basically you'll need to create an event for OnRowCreated and then - this is the key part - use the FindControl method to find the DropDownList and finally insert the items into the DDL.
Clarification: I thought your code in the OnLoad was trying to populate the DDL and I didn't see the code box scrolled down. Looks like your code is solid, I think you just need to switch from OnRowBinding to OnRowCreated
i'm trying to edit the information of Student table using gridview in c#
but my code updates the gridview without changing the table in my sql database
I don't know where is the problem
Here is my gridview :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="S_ID" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AllowPaging="true" >
<Columns>
<asp:TemplateField HeaderText="ID">
<EditItemTemplate>
<asp:TextBox ID="S_ID" runat="server" Text='<%# Eval("S_ID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("S_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="S_Name" runat="server" Text='<%# Eval("S_Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("S_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<EditItemTemplate>
<asp:TextBox ID="S_Email" runat="server" Text='<%# Eval("S_Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="S_Email" runat="server" Text='<%# Bind("S_Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
and this is the code behind:
protected void gvbind()
{
SqlConnection conn = new SqlConnection(#"MYCONNECTION");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT S_ID , S_Name , S_Email , B_ID FROM Student", conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt; // now assign this datatable dt to gridview as datasource
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
gvbind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
gvbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int sUserId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("S_Name"); //give the edititem template ID
TextBox email = (TextBox)GridView1.Rows[e.RowIndex].FindControl("S_Email");
try
{
SqlConnection conn = new SqlConnection(#"MYCONNECTION");
conn.Open();
SqlCommand c = new SqlCommand("Update Student set S_Name='" + name.Text + "',S_Email='" + email.Text + "'where S_ID='" + sUserId + "'");
c.Connection = conn;
c.ExecuteNonQuery();
GridView1.EditIndex = -1;
gvbind();
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(typeof(string), "Key", "alert('Error : \\n" + ex.Message + "');", true);
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
gvbind();
}
please can anyone help me why this change the gridview only but not the DB ?!
I think the first problem I've seen in your code is:
SqlCommand c = new SqlCommand("Update Student set S_Name='" + name.Text + "',S_Email='" + email.Text + "'where S_ID='" + sUserId + "'");
if S_ID column in your database is Integer then you shouldn't be using ' character
to indent the parameter sUserId it is just :
where S_ID = " + sUserId +")"