i want to edit the data in my gridview however it shows me an error that i dont know how to fix. can someone help me out please? here is my aspx page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Invalid" ForeColor="Red" ControlToValidate="TextBox1"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductDescription">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Invalid"
ForeColor="Red" ControlToValidate="TextBox2"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText ="ProductImage" DataImageUrlField="ProductImage" SortExpression="ProductImage" ControlStyle-Width ="10">
<ControlStyle Width="50px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="ProductQuantity">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid" ControlToValidate="TextBox3"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductPrice">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ErrorMessage="Invalid" ControlToValidate="TextBox4"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
<%--<asp:CommandField ShowDeleteButton="true" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete"
OnClientClick="return confirm('Confirm Delete?');"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
here is my code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Finding the controls from Gridview for the row which is going to update
//Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox ProductName = GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox;
TextBox ProductDescription = GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox;
TextBox ProductQuantity = GridView1.Rows[e.RowIndex].FindControl("TextBox3") as TextBox;
TextBox ProductPrice = GridView1.Rows[e.RowIndex].FindControl("TextBox4") as TextBox;
conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=Authorship;Integrated Security =True");
conn.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + ProductPrice + "' where ProductID='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
gvbind();
}
when i try to edit the data it shows me :
Conversion failed when converting the varchar value 'System.Web.UI.WebControls.TextBox' to data type int.
Line 64: //updating the record
Line 65: SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + ProductPrice + "' where ProductID='" + userid + "'", conn);
Line 66: cmd.ExecuteNonQuery();
Line 67: conn.Close();
Line 68: //Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
I think you should write Convert.ToInt32(ProductPrice.Text) instead of ProductPrice in your query.
like this`
SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + Convert.ToInt32(ProductPrice.Text) + "' where ProductID='" + userid + "'", conn);
Related
I'm trying to define try catch for a gridview in asp.net on C#, I have used several method such as show on the label or java script but they didn't work,
thanks to help me
here is my code
protected void AddNewSP(object sender, EventArgs e)
{
try
{
string Id = ((TextBox)GridView1.FooterRow.FindControl("txtId")).Text;
string PartName = ((TextBox)GridView1.FooterRow.FindControl("txtPartName")).Text;
string Coverage = ((TextBox)GridView1.FooterRow.FindControl("txtCoverage")).Text;
string SupplierName = ((TextBox)GridView1.FooterRow.FindControl("txtSupplierName")).Text;
string Status = ((TextBox)GridView1.FooterRow.FindControl("txtStatus")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into SupplySituation(Id, PartName, Coverage, SupplierName, Status) " +
"values(#Id, #PartName, #Coverage, #SupplierName, #Status);" +
"select Id, PartName, Coverage, SupplierName, Status from SupplySituation ORDER BY Id DESC";
cmd.Parameters.Add("#Id", SqlDbType.VarChar).Value = Id;
cmd.Parameters.Add("#PartName", SqlDbType.VarChar).Value = PartName;
cmd.Parameters.Add("#Coverage", SqlDbType.VarChar).Value = Coverage;
cmd.Parameters.Add("#SupplierName", SqlDbType.VarChar).Value = SupplierName;
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = Status;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');", true);
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
in fact there is no any error or any action , when I click on the "ADD" button with wrong data nothing happens, I except to show the error but nothing happens
my front code
<asp:GridView ID="GridView1" runat="server" Width="750px"
AutoGenerateColumns="False" Font-Names="Arial"
Font-Size="11pt" AlternatingRowStyle-BackColor="#C2D69B"
HeaderStyle-BackColor="green" AllowPaging="True" ShowFooter="True"
OnPageIndexChanging="OnPagingSP" OnRowEditing="EditSP"
OnRowUpdating="UpdateSP" OnRowCancelingEdit="CancelEditSP">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="lblId" runat="server"
Text='<%# Eval("Id")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtId" Width="20px"
MaxLength="5" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="PartName">
<ItemTemplate>
<asp:Label ID="lblPartName" runat="server"
Text='<%# Eval("PartName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPartName" runat="server"
Text='<%# Eval("PartName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtPartName" Width="100px"
MaxLength="20" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemStyle Width="30px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="100px" HeaderText="Coverage">
<ItemTemplate>
<asp:Label ID="lblCoverage" runat="server"
Text='<%# Eval("Coverage")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCoverage" runat="server"
Text='<%# Eval("Coverage")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCoverage" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="150px" HeaderText="SupplierName">
<ItemTemplate>
<asp:Label ID="lblSupplierName" runat="server"
Text='<%# Eval("SupplierName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtSupplierName" runat="server"
Text='<%# Eval("SupplierName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtSupplierName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="150px" HeaderText="Status">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"
Text='<%# Eval("Status")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStatus" runat="server"
Text='<%# Eval("Status")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtStatus" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument='<%# Eval("Id")%>'
OnClientClick="return confirm('Do you want to delete?')"
Text="Delete" OnClick="DeleteSP"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddNewSP" runat="server" Text="Add"
OnClick="AddNewSP" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
<HeaderStyle BackColor="Green" />
</asp:GridView>
Try to substitute your catch block
catch (Exception ex)
{
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + ex.Message.ToString() + "');", true);
}
with the following:
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('" + ex.Message.ToString() + "');", true);
}
I've coded a gridview that doesn't fire when I click the edit button and I found an older question that addresses my issue by just using e.CommandName with if statements under the RowCommand method. I'm trying to figure out how to implement it with my code.
My question is, how do I use e.RowIndex during update to find my controls and reference those now? Also, I've tried calling my old Update method but it won't let me use sender and e as parameters because GridviewCommandEventArgs is different from GridViewEventUpdateArgs. I'm pretty lost, any help would be appreciated in straightening this out.
C#:
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Edit")
{
}
if (e.CommandName == "Update")
{
UpdateCustomer(sender, e);
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=#Pid;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
cmd.Parameters.AddWithValue("#Pid", personID);
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
if (e.CommandName == "Cancel")
{
}
}
ASP.NET:
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" DataKeyNames="PersonID" runat="server" AutoGenerateColumns="False"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" ShowHeaderWhenEmpty="true" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width = "60px" />
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%#Bind("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can pass RowIndex as CommandArgument for your LinkButtons.
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" CommandArgument='<%# Container.DataItemIndex %>'>Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" CommandArgument='<%# Container.DataItemIndex %>'>Cancel</asp:LinkButton>
</EditItemTemplate>
Which can be access from code behind. Using rowindex you can get hold of the current row and find any controls using FindControl
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Update")
{
....
}
if (e.CommandName == "Cancel")
{
....
}
}
e.CommandArgument will contain the index of the row clicked, so you can access the relevant controls via
int index = Convert.ToInt32(e.CommandArgument);
GridView1.Rows[index].Controls[x];
I have a gridview that has insert, update, and delete functionality. On my update statement, I'm not sure how to set my identifier PersonID = to the currently selected identifier in the gridview that is being updated. Is there a common method that people use to achieve this functionality?
Code for Asp.net GRIDVIEW
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</itemtemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
<HeaderStyle BackColor="Aqua" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
Method for Update:
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=Person.PersonID;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
First specify DataKeyNames="PersonID" for your gridview definition.
Here is how you get the PersonID value in your UpdateCustomer function in code behind.
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
// assuming that the value of your PersonID is numeric value
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
....
}
The personID value you can pass as an argument to your WHERE clause.
Alternatively you can declare a HiddenField in your gridview and bind PersonID which you can access in you UpdateCustomer function using FindControl method.
I have a grid view it has 3 drop down lists and 3 text boxes in template field. On the top of the grid view i have two text boxes( text box 1 and 2) which initilize there values when page is loaded. i also have 3 buttons for add new row , save , search. I want my grid view to show data from database when search button is clicked i.e select * from table where text box 1 and 2 equal to some thing. My HTML looks like.
AutoGenerateColumns="false" onselectedindexchanged="Gridview1_SelectedIndexChanged" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Item name">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="119px"
DataTextField = "Item_name" Text='<%# Bind("Item_name") %>' DataValueField="Item_name"
AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub item">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" Height="25px" Width="119px"
AppendDataBoundItems="true"
DataValueField = "Sub_item" Text='<%# DataBinder.Eval(Container, "DataItem.Sub_item") %>' DataTextField = "Sub_item"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Location") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Permit number">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Permit no") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Applied">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
Height="25px" Width="119px"
DataTextField="Text" AppendDataBoundItems="true" Text='<%# DataBinder.Eval(Container, "DataItem.Applied") %>' DataValueField="Value" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Revision">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Revision") %>' ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonSave" runat="server" Text="Save" OnClick="Save_Click" />
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" />
<asp:Button ID="search" runat="server" Text="Search" OnClick="Search_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
on my search button click i have this code
if (TextBox4.Text != null && TextBox5.Text != null)
{
string job = TextBox4.Text.ToString();
string leg = TextBox5.Text.ToString();
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
Response.Write(job);
Response.Write(leg);
conn.Open();
SqlCommand comand = new SqlCommand("SELECT * from Billing_heads where job# = '" + job + "' AND leg#='" + leg + "' ", conn);
// try
//{
SqlDataAdapter adp = new SqlDataAdapter(comand);
DataSet ds = new DataSet();
adp.Fill(ds);
//gvPros is the ID of GridView.
Gridview1.DataSource = ds;
Gridview1.DataBind();
Please help me that how can i bind my gridview because in Text='<%# Bind("Item_name") %>' property it saying the column name it says property with name "coloumn name " does not exists please help
Data entered in textboxes is not getting updated in database. In debug mode I see that text1 and text2 in ItemUpdating event contain the same values as they had before calling ItemUpdating.
Here's my listview control:
<asp:ListView ID="ListView1" runat="server"
onitemediting="ListView1_ItemEditing"
onitemupdating="ListView1_ItemUpdating"
oniteminserting="ListView1_ItemInserting">
//LayoutTemplate removed
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("id")%>'></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%#Eval("text1")%>'></asp:Label>
<asp:LinkButton ID="LinkButton2" CommandName="Edit" runat="server">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton4" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("id")%>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Eval("text1")%>' TextMode="MultiLine" />
<asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("text2")%>' Height="100" TextMode="MultiLine" />
<asp:LinkButton ID="LinkButton1" CommandName="Update" CommandArgument='<%# Eval("id")%>' runat="server">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton5" CommandName="Cancel" runat="server">Cancel</asp:LinkButton>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Height="100"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server" Height="100" TextMode="MultiLine"></asp:TextBox>
<asp:LinkButton ID="LinkButton3" runat="server">Insert</asp:LinkButton>
</InsertItemTemplate>
</asp:ListView>
Codebehind file:
protected void ListView1_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView1.EditIndex = e.NewEditIndex;
BindList();
}
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
ListViewItem myItem = ListView1.Items[ListView1.EditIndex];
Label id = (Label)myItem.FindControl("Label1");
int dbid = int.Parse(id.Text);
TextBox text1 = (TextBox)myItem.FindControl("Textbox1");
TextBox text2 = (TextBox)myItem.FindControl("Textbox2");
//tried to work withNewValues below, but they don't work, "null reference" error is being thrown
//text1.Text = e.NewValues["text1"].ToString();
//text2.Text = e.NewValues["text2"].ToString();
//odbc connection routine removed.
//i know that there should be odbc parameteres:
comm = new OdbcCommand("UPDATE table SET text1 = '" + text1.Text + "', text2 = '" + text2.Text + "' WHERE id = '" + dbid + "'", connection);
comm.ExecuteNonQuery();
conn.Close();
ListView1.EditIndex = -1;
//here I databind ListView1
}
What's wrong with updating of text1.Text, text2.Text in ItemUpdating event? Should I use e.NewValues property? If so, how to use it?
Thanks in advance for any help.
Pffff. 2 days wasted. Just found out that I forgot to use to use in Page_Load():
if (!IsPostBack)
{
ListView1.DataSource = ds;
ListView1.DataBind();
}