I am trying to update a value in my gridview on row updating. However, it refuses to take in the value written in the textbox. I populate the gridview if the page is not post back. Help!
GRIDVIEW:
<asp:UpdatePanel runat="server" UpdateMode=Conditional><ContentTemplate>
<asp:GridView runat="server" ID="searchGV" AutoGenerateColumns="False" GridLines="None"
CssClass="mGrid" EmptyDataText="The Search Did Not Return Any Results"
PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Width="100%" OnRowCancelingEdit="searchGV_RowCancelingEdit"
OnRowEditing="searchGV_RowEditing" DataKeyNames="media_id" OnRowUpdating="searchGV_RowUpdating">
<Columns>
<asp:BoundField DataField="media_id" Visible="false" HeaderText="" />
<asp:BoundField DataField="dir_path" Visible="false" HeaderText="Dir" />
<asp:TemplateField HeaderText="Date Taken" >
<ItemTemplate>
<asp:LinkButton ID="dateLinkCsBtn" OnClientClick='<%#Eval("dir_path","Javascript:return test(\"{0}\",event);")%>'
runat="server" Text='<%# Bind("date") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Media Type">
<ItemTemplate>
<asp:Label runat="server" ID="mediaTypeLbl" Text='<%#Eval("description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alias File Name">
<ItemTemplate>
<asp:Label runat="server" ID="aliasFileName" Text='<%#Bind("alias_file_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%#Bind("alias_file_name") %>' ID="updateAliasTxt"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate></asp:UpdatePanel>
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
}
}
protected void searchGV_RowEditing(object sender, GridViewEditEventArgs e)
{
searchGV.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void searchGV_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
searchGV.EditIndex = -1;
FillGrid();
}
public void FillGrid()
{
Media_DAO media_query = new Media_DAO();
searchGV.DataSource = media_query.get_search_media(alias_file_name_txt.Text.Trim(), Convert.ToInt16(mediaTypeDDL.SelectedValue),
from_date_txt.Text.Trim(), to_date_txt.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.DataBind();
}
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = searchGV.Rows[e.RowIndex];
TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);
Media_DAO media_query2 = new Media_DAO();
media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.EditIndex = -1;
FillGrid();
}
while declaring the grid you have specified only 1 *data key value*
asDataKeyNames="media_id"
DateKeys for grid view is stored in array format starting from 0.
The error may be in getting the media_id while updating. You need to change it as follows.
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = searchGV.Rows[e.RowIndex];
TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
int media_id = Convert.ToInt16(e.Keys[0]); //this will get the media_id
Media_DAO media_query2 = new Media_DAO();
media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.EditIndex = -1;
FillGrid();
}
Since the earlier method was searchGV.DataKeys[e.RowIndex]["media_id"] , you might not get the media_id value if the row number which you are trying to edit is greater than 1.
The DataKeys property of GridView returns a collection of DataKey objects that represents the data key value of each row for a GridView. Thus, DataKeys[1] gives 2nd row, DataKeys[4] gives 5th row ...
Therefore, you need to use either the Value OR the Values property to access the value of a key field.
Rather than doing this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);
do this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Values["media_id"]);
// You can also use the Value property which gives the key value at index 0
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Value);
Related
I have a link button inside a gridView as below :
<asp:TemplateField HeaderText="Analyze">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Analyze" runat="server" OnClick="LinkButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
I have the LinkButton1_Click function as below :
protected void LinkButton1_Click(object sender, EventArgs e)
{
testtb.Text = name;
Console.WriteLine(name);
}
This variable "name" is the first column of the GridView.I am obtaining the value for "name" as below:
protected void UnanalysedGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView d = (DataRowView)e.Row.DataItem;
name = d["resultId"].ToString();
}
}
I want that on click of the link button the value of first column in that row of gridview becomes the text for the textbox testtb.
Somehow,the value for name remains null.
EDIT
I found out that probably RowDataBound isn't the correct event for my requirements because I need the value for each row.
So I removed the RowDataBound function.
I guess I have to handle this inside LinkButton1_Click itself.
I added this line to the function :
name = UnanalysedGV.SelectedRow.Cells[1].Text;
Still doesn't work.
Does anyone have any idea ?
You can do it using two approaches as mentioned below.
Handle click event of linkbutton through event bubbling code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging" OnRowCommand="grdCustomPagging_RowCommand">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("DealId") %>'
CommandName="VIEW">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCustomPagging_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "VIEW")
{
LinkButton lnkView = (LinkButton)e.CommandSource;
string dealId = lnkView.CommandArgument;
}
}
Handle click event of linkbutton directly click event code -
<asp:GridView AutoGenerateColumns="false" runat="server" ID="grdCustomPagging">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="RowNumber" />
<asp:BoundField DataField="DealId" HeaderText="DealID" />
<asp:BoundField DataField="Dealtitle" HeaderText="DealTitle" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" OnClick="lnkView_Click">View Deal</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void lnkView_Click(object sender, EventArgs e)
{
GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
string rowNumber = grdrow.Cells[0].Text;
string dealId = grdrow.Cells[1].Text;
string dealTitle = grdrow.Cells[2].Text;
}
Hope this helps.
So I'm using ADO.net Entity Data model in an ASP.Net (C#) Web page. I am dynamically adding and retrieving data to my database using gridviews. I am using master pages, and my gridview is in a contentplaceholder. My only issue with this code is that when my RowUpdating event fires, the gridview is null. I can call by BindGV function, and then the rest of the code updates the database perfectly fine, with the original data from the database I just bound to it, since the database was not updated yet. In all events, if I change bindGV() to Gridview1.databind(), the gridview is null. I think the datasource the gridview is referencing is becoming null at the end of the event when the data connection is closed, is there anyway to prevent this?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating"
onrowdatabound="GridView1_RowDataBound"
>
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Machine">
<ItemTemplate>
<asp:Label ID="lblMachine" runat="server" Text='<%# Eval("MachineName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtMachine" runat="server" Text='<%# Eval("MachineName") %>'></asp:TextBox>
</EditItemTemplate>
<ControlStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%# Eval("WorkCenterFK") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddldept" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="120px" />
</asp:TemplateField>
<asp:CommandField HeaderText="Actions" ShowEditButton="true" ShowDeleteButton="True"
ControlStyle-Width="50px" CausesValidation="false">
</asp:CommandField>
</Columns>
protected void BindGV()
{
QualityEntities database = new QualityEntities();
GridView1.DataSource = (from m in database.Machines
from d in database.Workcenters
where m.WorkcenterFK == d.id
select
new { id = m.id, MachineName = m.MachineName, WorkCenterFK = d.WorkCenterName }); ;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) BindGV();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGV();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGV();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
QualityEntities database = new QualityEntities();
BindGV();
Int32 id = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].FindControl("lblId")).Text);
DropDownList ddl = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddlDept"));
TextBox txt = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtMachine"));
Machine mch = (from m in database.Machines where m.id == id select m).Single();
mch.MachineName = txt.Text;
mch.WorkcenterFK = Convert.ToInt32(ddl.SelectedItem.Value);
database.SaveChanges();
GridView1.EditIndex = -1;
BindGV();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
QualityEntities database = new QualityEntities();
DropDownList temp = (DropDownList)(e.Row.FindControl("ddlDept"));
if (temp != null)
{
temp.DataSource = (from w in database.Workcenters select w);
temp.DataTextField = "WorkCenterName";
temp.DataValueField = "id";
temp.DataBind();
Int32 id = Convert.ToInt32(((Label)e.Row.FindControl("lblId")).Text);
}
}
Not sure why the GridView is null, but instead of using a member variable i would use the sender of the event which is always the source of the event (in this case the GridView)
// ...
GridView grid = (GridView)sender;
Int32 id = Convert.ToInt32(((Label)grid.Rows[e.RowIndex].FindControl("lblId")).Text);
// ...
<asp:GridView ID="gvGrid" runat="server" AutoGenerateColumns="False"
DataSourceID="dsDataSource" AllowPaging="True" PageSize="20" >
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1"
SortExpression="Field1" />
<asp:BoundField DataField="Field2" HeaderText="Field2"
SortExpression="Field2" />
<asp:TemplateField HeaderText="TemplateField1">
<ItemTemplate>
<asp:Label id="lblComments" runat="server" Text=" i use a function to compute"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Complete" HeaderText ="Status" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnComplete" runat="server" Text="Complete" onclick="btnComplete_Click"/>
<asp:Button ID="btnAddComment" runat="server" Text="Add Comment" onclick="btnAddComment_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnComplete_Click(object sender, EventArgs e)
{
String Field1 = gvGrid.SelectedRow.Cells[1].Text; // throws an error at runtime
//I want to be able to access the row data do some computation and then be able to insert it into the database
// Reason why I am trying to use it as a template field instead of a commandfield is because I want to make it not visible when it meets certain condition.
}
Also, it would be great if you could let me know a better way to do it, maybe using the command field and if there is a way to toggle its visibility. I don't mind using LinkButton either.
You can do it like this:
protected void btnComplete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.Parent.Parent;
//Alternatively you could use NamingContainer
//GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
Label lblComments = (Label)gvRow.FindControl("lblComments");
// lblComments.Text ...whatever you wanted to do
}
here is how you can access to the gridview row:
protected void btnComplete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvGrid.Rows)
{
Label lblComments = row.FindControl("lblComments") as Label;
....//you can do rest of the templatefiled....
}
}
I am trying to update the value of ajaxrating control and comments in the database`
` <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id"
onrowdatabound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="PurchasedPID" DataField="PurchasedPID"/>
<asp:BoundField HeaderText="DatetimePurchased" DataField="orderdate" />
<asp:BoundField HeaderText="MMBName" DataField="MMBName" />
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Rating RatingDirection="LeftToRightTopToBottom" Visible="true" AutoPostBack="true"
ID="Rating2" runat="server" MaxRating="5"
StarCssClass="star_rating" EmptyStarCssClass="star_empty"
FilledStarCssClass="star_filled" WaitingStarCssClass="star_saved" CurrentRating='<%# Bind("Rating") %>'
OnChanged="Rating2_Changed" >
</asp:Rating>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text= '<%# Bind("Comments") %>' multiline="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Submit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So I added the following rowcommand event on of the members suggestion.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Submit")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
Int32 Id = Convert.ToInt32(e.CommandArgument);
int ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
TextBox TextComments = row.FindControl("TextBox1") as TextBox;
string comments = TextComments.Text;
objBLL.UpdateRating(ratingScore, Id,comments);
}
But here instead of getting the new rating, it is inserting the CurrentRating in the table.
int ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
I think its because of this CurrentRating here.
Any idea how to get the value of updated rating? Or should i use an additional Rating_changed event to update the rate, and then a row command event to update the comments
Thanks
Sun
The easiest way to bind the your DataKey/ItemID to the Tag attribute of the Rating control
<asp:Rating RatingDirection="LeftToRightTopToBottom" Visible="true"
AutoPostBack="true"
ID="Rating2" runat="server" MaxRating="5" **Tag='<%# Bind("id")%>'**
StarCssClass="star_rating" EmptyStarCssClass="star_empty"
FilledStarCssClass="star_filled" WaitingStarCssClass="star_saved"
CurrentRating='<%# Bind("Rating") %>'
OnChanged="Rating2_Changed" >
</asp:Rating>
Event Handler
protected void Rating2_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
Rating r = sender as Rating;
int id = Convert.ToInt32(r.Tag);
objBLL.UpdateRating(Convert.ToInt32(e.Value),id)
}
You can use GridView1_RowCommand to update rating score in the DB. e.g.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Rating")
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
Int32 Id = Convert.ToInt32(e.CommandArgument);
ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
}
}
Set CommandName="Rating" to your linkbutton
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Rating">Submit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Hy,
I have a gridView control in Asp.NET like this:
<asp:GridView ID="outputGridView" runat="server" onrowediting="OutputGridView_RowEditing">
<asp:TemplateField ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="250px" HeaderText="JobId" HeaderStyle-HorizontalAlign="Left"
HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
<ItemTemplate>
<%# Eval("JobId")%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="250px" BorderWidth="1px"
BorderColor="#e1e1e1"></ItemStyle>
</asp:TemplateField>
</aspGridView>
On OutputGridView_RowEditing I have this code:
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow currentRow = outputGridView.Rows[e.NewEditIndex];
string JobId = currentRow.Cells[2].Text;
e.Cancel = true;
}
But in 'JobId' string its "", does anyone have any idea how can I get the text of the third cell from the row that is being edited?
Thank you,
Jeff
Ok what Bonshington said is correct, accept you want to add an id to the label.
<ItemTemplate>
<asp:Label ID="LblJobId" runat="server" Text='<%# Eval("JobId") %>' />
</ItemTemplate>
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow currentRow = outputGridView.Rows[e.NewEditIndex];
Label jobIdLabel = (Label)currentRow.Cells[2].FindControl("LblJobId");
string jobId = jobIdLabel.Text;
e.Cancel = true;
}
Please use Bind() method instead of Eval() method, it is for evaluation purpose only.
try to put it in literal cotnrol
<label><%# Eval("JobId")%></label>
and your jobID column will positioned as cell's child control
if you want to get GridViewRow currentRow you have to use
<Columns>
<asp:TemplateField>
<EditItemTemplate><asp:Label id="lbl" Text="<%# Eval("JobId")%>" /></EditItemTemplate>
</asp:TemplateField>
</Columns>
Auto-generated grid columns use Cells property
protected void OutputGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
OutputGridView.Rows[e.NewEditIndex].Cells[0]
}