I keep returning an error when trying to delete a row in my gridview (Input string was not in a correct format)
Not sure what I'm doing wrong. Any help?
<asp:GridView ID="favoritesGrid" runat="server" OnRowDeleting ="favoritesGrid_RowDeleting">
<columns>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True"/>
<asp:BoundField HeaderText="FavoritesId" DataField="FavoritesId"/>
<asp:TemplateField HeaderText="Site Name">
<ItemTemplate>
<asp:HyperLink ID="myHyperlink"
Text='<%# Eval("SiteName") %>'
NavigateUrl='<%# Eval("Url") %>'
runat="server">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
protected void favoritesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var delId = Convert.ToInt32(favoritesGrid.Rows[e.RowIndex].Cells[0].Text);
//var id = favoritesGrid.Rows[e.RowIndex].Cells[0].Text;
var delFavorites = new FavoritesDb();
var delFavs = delFavorites.DeleteFavorite(delId);
DataBind();
}
The cell at position 0 has the word "delete" in it and it cannot be converted to int.
You need to use:
var delId = Convert.ToInt32(favoritesGrid.Rows[e.RowIndex].Cells[1].Text);
However, this is not a good approach since you might change the cells order or add a new one. You'd better use the DataKeyNames attribute.
aspx:
<asp:GridView DataKeyNames="FavoritesId" ...>
C#:
Convert.ToInt32(favoritesGrid.DataKeys[e.RowIndex].Value);
Related
<!-- This is my ascx code -->
<asp:GridView ID="grid" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID" OnRowUpdating="grid_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="tb_Name" runat='server' Width="170px" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" HeaderText="Confirm" Text="Confirm" CommandName="Update" />
</Columns>
</asp:GridView>
//My ascx.cs code
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int rowIndex = e.RowIndex;
string productID = grid.DataKeys[rowIndex].Value.ToString();
int productId = Int32.Parse(productID);
GridViewRow gridRow;
gridRow = grid.Rows[rowIndex];
TextBox tname = (TextBox)gridRow.FindControl("tb_Name");
bool success = CatalogAccess.ProductUpdateItem(productId, tname.Text);
statusLabel.Text = success ? "Product successfully updated! " + tname.Text.ToString() : "There was an error updating the product";
PopulateControls();
}
My question is, how do i get the new TextBox value that I type in? I cant update, cuz im always getting that Eval value, not the new value that I type in?
Try to add postback method if(!ispostback) in load method and add grid binding method inside it
I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}
i have a repeater control which contains grids, based on values from database, say for example i have 2 grids inside repeater control, now both the grids contains a column which have up and down buttons, now when user clicks on the button from any grids, how can i check from which grid the button is called.
below is my code where i am filling the grids on RepeaterItemDataBound Event
GridView gvw = e.Item.FindControl("grid") as GridView;
gvw.DataSource = info.GetStories(sectionNames[e.Item.ItemIndex].Trim());
gvw.DataBind();
here section name contains the name of the sections, based on number of sections, i generate the grids.
My Design looks like this:
<asp:Repeater ID="rptGrids" runat="server"
OnItemDataBound="rptGrids_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="grid" runat="server" Width="100%" CellPadding="5" AllowPaging="true" ShowHeader="true" PageSize="10" AutoGenerateColumns="false" OnRowCommand="Stories_RowCommand">
<Columns>
<asp:BoundField DataField="ArticleID" HeaderText="Article ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="CategoryID" HeaderText="Category ID" ItemStyle-CssClass="center" />
<asp:BoundField DataField="Title" HeaderText = "Article Title" />
<asp:BoundField DataField="PublishDate" DataFormatString="{0:d}" HeaderText="Publish Date" ItemStyle-CssClass="center" />
<asp:TemplateField HeaderText="Select Action" ItemStyle-CssClass="center">
<ItemTemplate>
<asp:ImageButton ID="btnMoveUp" runat="server" ImageUrl="/images/up.gif" CommandArgument="Up" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnMoveDown" runat="server" ImageUrl="/images/dn.gif" CommandArgument="Down" CommandName='<%# Container.DataItemIndex + "," + DataBinder.Eval(Container.DataItem, "StoryType") %>' />
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="/images/deny.gif" CommandArgument="Delete" OnClientClick="return confirm('Are you sure you want to delete this article?');" CommandName='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:HiddenField ID="hdStoriesSortOrder" runat="server" Value='<%# Eval("SortOrder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div class="blank"></div>
</ItemTemplate>
</asp:Repeater>
this is my gridviews row_command event
protected void Stories_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandName.Split(',')[0]);
string section = e.CommandName.Split(',')[1].Trim().ToString();
string command = e.CommandArgument.ToString();
if (command.ToLower() == "up")
{
GridView grd = rptGrids.Items[1].FindControl("grid") as GridView; // If i specify the index here, i gets proper grid, but how to recognize at runtime.
Response.Write(grd.Rows.Count);
}
else if (command.ToLower() == "down")
{
}
}
can anyone tell me how can i get from which grid up/down button has been clicked.
You can use command argument to pass required value.
Here is sample of using imagebutton in similar way:
<asp:ImageButton ID="btnView" runat="server" ToolTip="<% $resources:AppResource,Edit %>"
SkinID="EditPage" CommandName="myCommand" CommandArgument='<%# Eval("CustomerId") %>'
PostBackUrl='<%# "~/AdminPages/Customer.aspx?id=" + Eval("CustomerId").ToString() %>' />
Take notice on CommandArgument property.You can set it with value that indicates specific gridview inside repeater.
And here is how to check the value:
protected void EntityGridViewContacts_RowCommand(object sender, GridViewCommandEventArgs e)
{
//here you can check for command name...
switch (e.CommandName)
{
case "myCommand":
//here you access command argument...
int customerId = Convert.ToInt32(e.CommandArgument.ToString());
break;
}
//here is how you access source gridview...
GridView gridView = (GridView)sender;
string controlId = gridView.ID;
}
You can also set CommandArgument using this approach:
CommandArgument='<%# GetMySpecialValue() %>'
Then you should declare function on page side something like this:
public string GetMySpecialValue()
{
return "some value";
}
I am having a grid view created by using template fields. I inserted a link button using template fields in the grid view.
There are 4 textboxes outside the GridView.. i want to select the row on link button's click and put the selected row's data in text boxes. I am using a row command even for this but its not working ... the syntax i am using is .:
<asp:GridView ID="gview" AutoGenerateColumns="False" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" onrowcommand="gview_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Book Name">
<ItemTemplate>
<%#Eval("book_name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Author">
<ItemTemplate>
<%#Eval("book_author") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Publisher">
<ItemTemplate>
<%#Eval("book_Publisher") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Book Price">
<ItemTemplate>
<%#Eval("book_Price") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:LinkButton ID="lnkDet" CommandName="cmdBind" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" runat="server" CausesValidation="false">View Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
and Code behind file :
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdBind")
{
LinkButton lb = (LinkButton)e.CommandSource;
int index = Convert.ToInt32(lb.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}
}
Can anyone tell me how to do this.
I think this works:
protected void gview_RowCommand(object sender, GridViewCommandEventArgs e){
if (e.CommandName == "cmdBind")
{
int index = Convert.ToInt32(e.CommandArgument);
//Bind values in the text box of the pop up control
txt_name.Text = gview.Rows[index].Cells[0].Text;
txt_author.Text = gview.Rows[index].Cells[1].Text;
txt_price.Text = gview.Rows[index].Cells[2].Text;
}}
Attempting it the way you are is not impossible, but it may be easier to just use the in built select buttons for each row. That way you can just use the SelectedIndexChanged event of the gridview:
protected void gview_SelectedIndexChanged(object sender, EventArgs e)
{
txt_name.Text = gview.SelectedRow.Cells[0].Text;
txt_author.Text = gview.SelectedRow.Cells[1].Text;
txt_price.Text = gview.SelectedRow.Cells[2].Text;
}
I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}
I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.
After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >