Why is the Update Control of Gridview is behaving abnormally? - c#

Here is my code for updating the gridview rows. But what it does it shows this behavior which I guess is not what it usually does. Please point out what did I do wrong.
This is an image showcasing what is happening.
The code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindgrid();
}
}
private void bindgrid()
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from vendor";
MySqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
And this is ASPX code:
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit Element" CssClass="btn btn-success fa fa-edit" ID="Editbutton" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" CssClass="btn btn-success fa fa-edit" ID="updatebutton" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" CssClass="btn btn-warning fa fa-close" ID="cancelbutton" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%# Eval("v_id")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="idtext" runat="server" Text='<%# Eval("v_id")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor Name">
<ItemTemplate>
<asp:Label ID="namelbl" runat="server" Text='<%# Eval("v_name")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="nametext" runat="server" Text='<%# Eval("v_name")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

Related

OnRowCommand is triggered, OnRowEditing not firing on my gridview

I have a gridview like below:
<asp:GridView ID="gvitems" runat="server" AutoGenerateColumns="false" CssClass="GridStyle" AllowSorting="true" OnSorting="OnSorting" DataKeyNames="Id" OnRowCommand="gv_RowCommand"
OnRowEditing="gv_RowEditing" OnRowUpdating="gv_RowUpdating" OnRowCancelingEdit="gv_RowCancelEdit" >
<Columns>
<asp:buttonfield buttontype="Link"
commandname="View"
text="View"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button runat="server" Text="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Next Steps">
<ItemTemplate>
<asp:Label runat="server" ID="lblNextSteps" Text='<%# Eval("NextSteps")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtNextSteps" Text='<%# Eval("NextSteps")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="txtNextStepsFooter"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the backend, this is how i fill it with data:
DataSet dataSet = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid_SubmittedProjects();
}
}
private void BindGrid_SubmittedProjects(string sortExpression = null)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ProjectsDataBase"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("ViewProjects", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = "myusername";
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
dataSet = new DataSet();
sda.Fill(dataSet, "Project");
}
gvitems.DataSource = dataSet.Tables[0].DefaultView;
gvitems.DataBind();
}
}
}
When I click on the "View" hyperlink on each row, it works, so OnRowCommand function below is triggered.
protected void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
//my work
}
}
However, when I click on "Edit" button, nothing is happening, OnRowEditing is not being triggered.
protected void gv_RowEditing(Object sender, GridViewEditEventArgs e)
{
gvitems.EditIndex = e.NewEditIndex;
this.BindGrid_SubmittedProjects();
}
protected void gv_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
//my update query.
}
I could not see what I am doing wrong. Tried many things I've found over online but none worked. Any help would be so appreciated.
Regards.
Using LinkButton instead of regular button fixed the issue.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Tasklist'

I'm making a page with two gridviews, where the event on one is responsible for the content in another. (Like if you have a task and you task has some steps, so when you click on a task from a list of tasks you can see a table of steps associated with that task)
But I'm facing the exception as above. Can anyone please help me solve it?
index.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<!-- Bootstrap core CSS-->
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<!-- Custom styles for this template -->
<link href="../Styles/dashboard.css" rel="stylesheet" />
<style>
td, th
{
border-color: rgb(222, 226, 230);
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class='table - responsive'>
<asp:GridView ID="tasklistsGridView" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="Id" AllowPaging="True" CellPadding="3" OnPageIndexChanging="tasklistsGridView_PageIndexChanging" OnRowDeleting="tasklistsGridView_RowDeleting" OnRowEditing="tasklistsGridView_RowEditing" OnRowUpdating="tasklistsGridView_RowUpdating" OnRowCancelingEdit="tasklistsGridView_RowCancelingEdit" PageSize="4" BackColor="#ffffff" BorderColor="#ffffff" BorderStyle="Solid" BorderWidth="0px" CellSpacing="2" OnRowCommand="tasklistsGridView_RowCommand" class='table table - striped table - sm' OnSelectedIndexChanged="tasklistsGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" Width="100px" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtName" runat="server" Width="100px"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" Width="100px" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDescription" Width="100px" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Prerequisites" SortExpression="Prerequisites">
<EditItemTemplate>
<asp:TextBox ID="txtPrerequisites" Width="100px" runat="server" Text='<%# Bind("Prerequisites") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtPrerequisites" Width="100px" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Prerequisites") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Workgroup" SortExpression="Workgroup">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="Id">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="Id">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Workgroup") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tag" SortExpression="Tag">
<EditItemTemplate>
<asp:TextBox ID="txtTag" Width="100px" runat="server" Text='<%# Bind("Tag") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtTag" Width="100px" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Tag") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="Objectives" ShowSelectButton="True" ShowHeader="True" />
</Columns>
<EmptyDataTemplate>
<h3>No available tasklists! Create a new one?</h3>
<form role="form">
<div class="form-group">
<label class="control-label" for="name">Name</label>
<asp:TextBox ID="newTasklistName" type="text" class="form-control" placeholder="Enter Tasklist Name" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<label class="control-label" for="description">Description</label>
<asp:TextBox ID="newTasklistDescription" type="text" class="form-control" placeholder="Describe your Tasklist" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<label class="control-label" for="prerequisites">Prerequisites</label>
<asp:TextBox ID="newTasklistPrerequisites" type="text" class="form-control" placeholder="Enter Prerequisites for your Tasklist" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<div class="btn-group dropdown">
<asp:Button ID="workgroupDropdownLabel" type="button" class="btn btn-light dropdown-toggle" runat="server" Text="Workgroups" style="padding-left: 0.4em;" />
<asp:DropDownList ID="workgroupDropdown" type="button" class="btn btn-light" runat="server" style="position:relative; left:-0.3em; top: 0.1em; padding-left: 0.1em;" DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="Id"></asp:DropDownList>
</div>
</div>
<div class="form-group">
<label class="control-label" for="tag">Tag</label>
<asp:TextBox ID="newTasklistTag" type="text" class="form-control" placeholder="Tag your Tasklist" runat="server"></asp:TextBox>
</div>
<asp:Button ID="newTasklistSubmitButton" class="btn btn-default" runat="server" Text="Submit" />
</form>
</EmptyDataTemplate>
<%--<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />--%>
<SelectedRowStyle BackColor="#505050" Font-Bold="True" ForeColor="White" />
<%--<HeaderStyle BackColor="white" Font-Bold="True" ForeColor="White" />--%>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SOP3ConnectionString %>" SelectCommand="SELECT [name], [Id] FROM [workgroup]" ProviderName="System.Data.SqlClient"></asp:SqlDataSource>
<div class='table - responsive'>
<asp:GridView ID="objectivesGridView" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="Id" AllowPaging="True" CellPadding="3" OnPageIndexChanging="objectivesGridView_PageIndexChanging" OnRowDeleting="objectivesGridView_RowDeleting" OnRowEditing="objectivesGridView_RowEditing" OnRowUpdating="objectivesGridView_RowUpdating" OnRowCancelingEdit="objectivesGridView_RowCancelingEdit" PageSize="5" BackColor="#ffffff" BorderColor="#ffffff" BorderStyle="None" BorderWidth="0px" CellSpacing="2" OnRowCommand="objectivesGridView_RowCommand" class='table table - striped table - sm'>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" />
<asp:TemplateField HeaderText="Objective" SortExpression="Objective">
<EditItemTemplate>
<asp:TextBox ID="txtObjective" Width="100px" runat="server" Text='<%# Bind("Objective") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtObjective" runat="server" Width="100px"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Objective") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tasklist" SortExpression="Tasklist">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="name" DataValueField="Id">
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource2" DataTextField="name" DataValueField="Id">
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Tasklist") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
</Columns>
<EmptyDataTemplate>
<h3>No available objectives for the selected tasklist! Create a new one?</h3>
<form role="form">
<div class="form-group">
<label class="control-label" for="name">Name</label>
<asp:TextBox ID="newObjective" type="text" class="form-control" placeholder="Enter Objective" runat="server"></asp:TextBox>
</div>
<div class="form-group">
<div class="btn-group dropdown">
<asp:Button ID="tasklistDropdownLabel" type="button" class="btn btn-light dropdown-toggle" runat="server" Text="Tasklists" style="padding-left: 0.4em;" />
<asp:DropDownList ID="tasklistDropdown" type="button" class="btn btn-light" runat="server" style="position:relative; left:-0.3em; top: 0.1em; padding-left: 0.1em;" DataSourceID="SqlDataSource2" DataTextField="name" DataValueField="Id"></asp:DropDownList>
</div>
</div>
<asp:Button ID="newObjectiveSubmitButton" class="btn btn-default" runat="server" Text="Submit" />
</form>
</EmptyDataTemplate>
<%--<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />--%>
<SelectedRowStyle BackColor="#505050" Font-Bold="True" ForeColor="White" />
<%--<HeaderStyle BackColor="white" Font-Bold="True" ForeColor="White" />--%>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString2 %>" SelectCommand="SELECT [name], [Id] FROM [tasklist]" ProviderName="System.Data.SqlClient"></asp:SqlDataSource>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="../Scripts/jquery-3.3.1.slim.min.js"></script>
<script>window.jQuery || document.write('<script src="../Scripts/jquery-3.3.1-slim.min.js"><\/script>')</script>
<script src="../Scripts/umd/popper.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<!-- Icons -->
<script src="../Scripts/feather.min.js"></script>
<script>
feather.replace()
</script>
<!-- Custom Scripts -->
<script>
var tables = document.getElementsByTagName('table');
for (var i = 0; i < tables.length; i++)
{
document.getElementsByTagName('table')[i].className += " table-hover";
document.getElementsByTagName('table')[i].className += " thead-dark";
document.getElementsByTagName('table')[i].className += " table-responsive-sm";
}
</script>
</form>
index.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class index : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand();
DataTable table = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
showTasklists();
}
}
private void showTasklists()
{
try
{
command.Connection = connection;
command.CommandText = "select * from tasklist";
adapter = new SqlDataAdapter(command);
adapter.Fill(table);
tasklistsGridView.DataSource = table;
tasklistsGridView.DataBind();
}
catch (Exception x)
{
Response.Write("Exception: " + x.Message);
}
}
protected void tasklistsGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
tasklistsGridView.PageIndex = e.NewPageIndex;
showTasklists();
}
protected void tasklistsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
command.Connection = connection;
command.CommandText = "delete from tasklist where Id='" + tasklistsGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
showTasklists();
}
catch (Exception x)
{
Response.Write("Exception: " + x.Message);
}
}
protected void tasklistsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
tasklistsGridView.EditIndex = e.NewEditIndex;
showTasklists();
}
protected void tasklistsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtName = (TextBox)tasklistsGridView.Rows[e.RowIndex].FindControl("txtName");
TextBox txtDescription = (TextBox)tasklistsGridView.Rows[e.RowIndex].FindControl("txtDescription");
TextBox txtPrerequisites = (TextBox)tasklistsGridView.Rows[e.RowIndex].FindControl("txtPrerequisites");
DropDownList ddlWorkgroup = (DropDownList)tasklistsGridView.FooterRow.FindControl("DropDownList1");
TextBox txtTag = (TextBox)tasklistsGridView.Rows[e.RowIndex].FindControl("txtTag");
command.Connection = connection;
command.CommandText = "update tasklist set name ='" + txtName.Text + "',description ='" + txtDescription.Text + "',prerequisites ='" + txtPrerequisites.Text + "',workgroup ='" + ddlWorkgroup.SelectedItem.ToString() + "',tag ='" + txtTag.Text + "' WHERE Id='" + tasklistsGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
connection.Open();
command.ExecuteNonQuery();
tasklistsGridView.EditIndex = -1;
showTasklists();
connection.Close();
}
catch (Exception x)
{
Response.Write("Exception: " + x.Message);
}
}
protected void tasklistsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
tasklistsGridView.EditIndex = -1;
showTasklists();
}
protected void tasklistsGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtName = (TextBox)tasklistsGridView.FooterRow.FindControl("txtName");
TextBox txtDescription = (TextBox)tasklistsGridView.FooterRow.FindControl("txtDescription");
TextBox txtPrerequisites = (TextBox)tasklistsGridView.FooterRow.FindControl("txtPrerequisites");
DropDownList ddlWorkgroup = (DropDownList)tasklistsGridView.FooterRow.FindControl("DropDownList1");
TextBox txtTag = (TextBox)tasklistsGridView.FooterRow.FindControl("txtTag");
command.Connection = connection;
command.CommandText = "insert into tasklist(name, description,prerequisites,workgroup,tag) Values('" + txtName.Text + "', '" + txtDescription.Text + "', '" + txtPrerequisites.Text + "', '" + ddlWorkgroup.SelectedItem.ToString() + "', '" + txtTag.Text + "')";
connection.Open();
command.ExecuteNonQuery();
showTasklists();
connection.Close();
}
}
catch (Exception x)
{
Response.Write("Exception: " + x.Message);
}
}
protected void tasklistsGridView_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["tasklistid"] = tasklistsGridView.SelectedRow.Cells[0].Text;
try
{
//2. Open Connection
connection.Open();
//3. Create and Execute Command
string query = "select Id, objective from objectives where tasklistId='" + Convert.ToInt32(ViewState["tasklistid"]) + "';";
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
DataTable Table = new DataTable();
Table.Load(reader);
objectivesGridView.DataSource = Table;
objectivesGridView.DataBind();
//4. Close connection
connection.Close();
}
catch (Exception x)
{
Response.Write("exception: " + x.Message);
}
}
private void showObjectives()
{
try
{
command.Connection = connection;
command.CommandText = "select * from objectives";
adapter = new SqlDataAdapter(command);
adapter.Fill(table);
objectivesGridView.DataSource = table;
objectivesGridView.DataBind();
}
catch (Exception x)
{
Response.Write("showObjectivesException: " + x.Message);
}
}
protected void objectivesGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
objectivesGridView.PageIndex = e.NewPageIndex;
showObjectives();
}
protected void objectivesGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
command.Connection = connection;
command.CommandText = "delete from objectives where Id='" + objectivesGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
showObjectives();
}
catch (Exception x)
{
Response.Write("objectivesGridView_RowDeletingException: " + x.Message);
}
}
protected void objectivesGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
objectivesGridView.EditIndex = e.NewEditIndex;
showObjectives();
}
protected void objectivesGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtObjective = (TextBox)objectivesGridView.Rows[e.RowIndex].FindControl("txtObjective");
DropDownList ddlObjectives = (DropDownList)objectivesGridView.FooterRow.FindControl("DropDownList2");
command.Connection = connection;
command.CommandText = "update objectives set objective ='" + txtObjective.Text + "',tasklistId ='" + ddlObjectives.SelectedItem + "' WHERE Id='" + objectivesGridView.DataKeys[e.RowIndex].Values[0].ToString() + "'";
connection.Open();
command.ExecuteNonQuery();
objectivesGridView.EditIndex = -1;
showObjectives();
connection.Close();
}
catch (Exception x)
{
Response.Write("objectivesGridView_RowUpdatingException: " + x.Message);
}
}
protected void objectivesGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
objectivesGridView.EditIndex = -1;
showObjectives();
}
protected void objectivesGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtObjective = (TextBox)objectivesGridView.FooterRow.FindControl("txtObjective");
DropDownList ddlObjective = (DropDownList)objectivesGridView.FooterRow.FindControl("DropDownList2");
command.Connection = connection;
command.CommandText = "insert into objectives(objective,tasklistId) Values('" + txtObjective.Text + "', '" + ddlObjective.SelectedItem + "')";
connection.Open();
command.ExecuteNonQuery();
showObjectives();
connection.Close();
}
}
catch (Exception x)
{
Response.Write("objectivesGridView_RowCommandException: " + x.Message);
}
}
}
Here's the output snap (you might want to look at that red arrow on the top)
Check if all your queries return a field named Tasklist
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Tasklist")%>'></asp:Label>

How to get data from TextBox in gridview?

This is the code where I have problem, I don't have any problems in the previous page but this is happening in this and following page.
<asp:GridView ID="gv_employee" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="false" OnRowEditing="Edit" OnRowCancelingEdit="CancelEdit" OnRowUpdating="Update" Width="1070px"
AlternatingRowStyle-BackColor="WhiteSmoke" HeaderStyle-BackColor="#C5D9F1">
<Columns>
<asp:TemplateField HeaderText="S.No" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="60px">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Code" ItemStyle-Width="160px">
<ItemTemplate>
<asp:Label ID="lbl_gv_empcode" runat="server" Text='<%#Eval("employeecode")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Label ID="lbl_gv_empname" runat="server" Text='<%#Eval("employeename") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_empname" runat="server" Text='<%#Eval("employeename") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address1">
<ItemTemplate>
<asp:Label ID="lbl_gv_addr1" runat="server" Text='<%#Eval("address1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_addr1" runat="server" Text='<%#Eval("address1") %>' />
</EditItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Address2">
<ItemTemplate>
<asp:Label ID="lbl_gv_addr2" runat="server" Text='<%#Eval("address2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_addr2" runat="server" Text='<%#Eval("address2") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address3">
<ItemTemplate>
<asp:Label ID="lbl_gv_addr3" runat="server" Text='<%#Eval("address3") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_addr3" runat="server" Text='<%#Eval("address3") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lbl_gv_city" runat="server" Text='<%#Eval("city")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_city" runat="server" Text='<%#Eval("city")%>' />
</EditItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lbl_gv_email" runat="server" Text='<%#Eval("email") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_email" runat="server" Text='<%#Eval("email") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label ID="lbl_gv_phone" runat="server" Text='<%#Eval("phone") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_gv_phone" runat="server" Text='<%#Eval("phone") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btndel" runat="server" Text="Delete" CommandArgument='<%#Eval("employeecode") %>'
OnClientClick="return confirm('Do you want to delete?')" OnClick="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my asp code
public void BindData()
{
string ls_sqlcmd = "select * from employeemst";
SqlCommand cmd = new SqlCommand(ls_sqlcmd);
gv_employee.DataSource = add.GetData(cmd);
gv_employee.DataBind();
}
protected void Delete(object sender, EventArgs e)
{
LinkButton lnk_deletestate = (LinkButton)sender;
string str = "delete from employeemst where employeecode='" + lnk_deletestate.CommandArgument + "'";
add.adddata(str);
BindData();
}
protected void Update(object sender, GridViewUpdateEventArgs e)
{
String emplname = ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_empname")).Text;
String Addr1= ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_addr1")).Text;
String addr2 = ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_addr2")).Text;
String addr3 = ((TextBox)gv_employee.Rows[e.RowIndex].FindControl("txt_gv_addr3")).Text;
gv_employee.EditIndex = -1;
BindData();
}
protected void Edit(object sender, GridViewEditEventArgs e)
{
gv_employee.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gv_employee.EditIndex = -1;
BindData();
}
}
This is my aspx.cs code.
My problem is that I am unable to get data from textbox which is in gridview <EditItemTemplate></EditItemTemplate>
I don't get updated value in string emplname, addr1, addr2,addr3.
your issue is you are binding grid view in each postback, move your BindData method inside the IsPostBack check, then you can get the data
protected void Page_Load(object sender, EventArgs e)
{
Session["page"] = "Employee";
if (!IsPostBack)
{
BindData();
DataTable dt = add.retrive("select * from statemst");
for (int i = 0; i < dt.Rows.Count; i++)
{
ListItem item = new ListItem();
item.Text = dt.Rows[i]["statedesc"].ToString();
item.Value = dt.Rows[i]["statecode"].ToString();
ddl_state.Items.Add(item);
}
}
}

Gridview update button

I have a GridView with a button which sets all rows into edit mode (which is what I want). However I was wondering if there is a way to create a button that will update the whole gridview with my changes. Here is the code behind this.
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
onrowcommand="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="labelID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat="server" Text='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="labelfirstname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' />
<asp:TextBox ID="txtFirstName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="labellastname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' />
<asp:TextBox ID="txtLastName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Edit Mode" onclick="Button1_Click1" />
<asp:Button ID="Button2" runat="server" Text="View Mode" onclick="Button2_Click1" />
And here is the c#
private bool isEditMode = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=LiquorStore;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT id, firstname, lastname, nickname FROM Company", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
}
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
protected void gvUsers_RowDataBound(object sender, GridViewCommandEventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
isEditMode = true;
BindData();
}
protected void Button2_Click1(object sender, EventArgs e)
{
isEditMode = false;
BindData();
}
Thank you in advance!!
You can iterate thru you rows and get values in a textbox for specific row
foreach (GridViewRow row in gvUsers.Rows)
{
TextBox txtFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox txtLastName = row.FindControl("txtLastName") as TextBox;
if (txtFirstName.Text!="" && txtLastName.Text!="")
{
// do what you need with values
}
}

How to carry out edit mode to update datas in Datalist control?

i have a datalist control
<ItemTemplate>
<asp:Label ID="lblAddressID" runat="server" Text='<%# Bind("StudentName") %>'/>
<asp:Label ID="lbl" runat="server" />
<asp:Button runat="Server" ID="cmdEdit" CommandName="Edit" Text="Edit"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAddressID" runat="server" Text='<%# Bind("StudentName") %>' BackColor="#FFFF66" />
<%-- <asp:Label ID="lbl" runat="server"/>
<asp:Button runat="Server" ID="cmdUpdate" CommandName="Update" Text="Update" />
<asp:Button runat="Server" ID="cmdCancel" CommandName="Cancel" Text="Cancel"/>--%>
</EditItemTemplate>
</asp:DataList>
and during page load im binding the datas:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt = obj.GetDatas();
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
now i received the datas binded to the control. i need to update my datas in edit mode.
How to carry out edit mode to update datas in Datalist control ??
any help...
have look at this sample
EditItemTemplate and DataList
source code:
DataList3_cs.aspx

Categories

Resources