Passing value of textbox to a class VS2013 ASPX C# - c#

I have a Gridview.aspx, Gridview.aspx.cs and GetData.cs (class)
In Gridview.aspx I have a textbox named SearchData and a button named SearchBtn
I have this in my Gridview.aspx.cs >>>
protected void SearchBtn_Click(object sender, EventArgs e){
if (!IsPostBack){
Search_Grid();
}
}
void Search_Grid(){
DataGridView.DataSource = obj.Search_Data();
DataGridView.DataBind();
}
And since it's my first time to use a class, here's what i put in GetData.cs >>>
public DataTable Search_Data(){
adap = new SqlDataAdapter("select * from MyTable " +
"where MyID = '" +
value_of_my_SearchData_textbox +
"'", con);
dt = new DataTable();
adap.Fill(dt);
return dt;
}
ASPX Code
GridView.aspx code is long, but here's what under the gridview part:
<table id="TBL_GridView" runat="server" align="center">
<tr>
<td text-align:center">*** TEST ONLY ***</td>
</tr>
<tr>
<td >
<asp:Label ID="Label1" runat="server" Text="Procedure name: "></asp:Label>
<asp:TextBox ID="SearchData" runat="server"></asp:TextBox>
<asp:Button ID="SearchBtn" runat="server" Text="Search" OnClick="SearchBtn_Click" />
</td>
</tr>
<tr >
<td >
<asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" ShowFooter="True"
CellPadding="4" ForeColor="#333333" GridLines="None" Height="281px" style="margin-top: 0px" Width="1000px"
OnRowCancelingEdit="DataGridView_RowCancelingEdit"
OnRowEditing="DataGridView_RowEditing" HorizontalAlign="Center" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>Recipe Name</HeaderTemplate>
<ItemTemplate><asp:Label ID="recpname" runat="server" Text='<%# Bind("recpname")%>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="recpname" runat="server"></asp:TextBox></EditItemTemplate>
<FooterTemplate><asp:TextBox ID="recpname" runat="server"></asp:TextBox></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Standard Time</HeaderTemplate>
<ItemTemplate><asp:Label ID="stdtime" runat="server" Text='<%# Bind("stdtime")%>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="stdtime" runat="server"></asp:TextBox></EditItemTemplate>
<FooterTemplate><asp:TextBox ID="stdtime" runat="server"></asp:TextBox></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Edit" CommandName="Edit" Width="60px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" runat="server" Text="Update" CommandName="Update" Width="60px" />
<asp:Button ID="BtnCancle" runat="server" Text="Cancel" CommandName="Cancel" Width="60px" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="BtnInsert" runat="server" Text="Insert" Width="60px" OnClick="BtnInsert_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</td>
</tr>
</table>
How should I pass the value of my textbox to my class?

I see that your text box SearchData is just an ordinary textbox outside of gridview and not in the gridview.
You can simply use:
SearchData.Text
Change the methods to pass SearchData.Text
protected void SearchBtn_Click(object sender, EventArgs e){
if (!IsPostBack){
Search_Grid(SearchData.Text);
}
}
void Search_Grid(string searchValue){
DataGridView.DataSource = obj.Search_Data(searchValue);
DataGridView.DataBind();
}
Finally use it:
public DataTable Search_Data(string searchValue){
adap = new SqlDataAdapter("select * from MyTable " +
"where MyID = '" +
searchValue +
"'", con);
dt = new DataTable();
adap.Fill(dt);
return dt;
}
However, note this code is prone to SQL Injection attack because you are adding value inline, so an attacker can add ; delete from my table to wipe your data.
You should parameterize your query.
adap = new SqlDataAdapter("select * from MyTable where MyID = #myIdValue", con);

Related

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>

GridView_RowUpdating not firing

I have Gridview with ItemTemplate and EditItemTemplate:
But when i click "Ok" button, nothing happens. I tried to put trace point on RowUpdating event and click "Ok" button, but its not even triggered. I assume, that problem could be in the same "Id" of ItemTemplate and EditItemTemplate lbl_first_fl. But earlier this worked fine, the only thing was changed - i updated Visual studio to 2015 and changed Windows to 8. So i installed VS 2013, but problem still occures. Any suggestions? Or maybe how can i deal with it using different id's?
aspx page:
<asp:GridView ID="GridView5" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" Height="430px" OnRowCancelingEdit="GridView5_RowCancelingEdit" OnRowDataBound="GridView5_RowDataBound" OnRowEditing="GridView5_RowEditing" OnRowUpdating="GridView5_RowUpdating" Width="100%" CssClass="gridview" GridLines="none">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField ItemStyle-Width="100">
<EditItemTemplate>
<asp:Button ID="btn_Update_fl" runat="server" CommandName="Update" Text="Ок" />
<asp:Button ID="btn_Cancel_fl" runat="server" CommandName="Cancel" Text="Отмена" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btn_Edit_fl" runat="server" CommandName="Edit" Text="✎" Enabled='<%# Flag %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="08:00 - 17:00" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="true"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_first_fl" runat="server" Text='<%# Eval("First") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_first_fl" runat="server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField/>
</Columns>
</asp:GridView>
OnRowUpdating event:
protected void GridView5_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
DropDownList First_fl = GridView5.Rows[e.RowIndex].FindControl("ddl_first_fl") as DropDownList;
con = new SqlConnection(cs);
con.Open();
//updating the record
SqlCommand cmd_fl = new SqlCommand("Update [Duty].[dbo].[Schedule_FirstLine] set First='" + First_fl.Text + "', con);
cmd_fl.ExecuteNonQuery();
con.Close();
GridView5.EditIndex = -1;
ShowDataFirstLine();
}
Binding Gridview:
protected void ShowDataFirstLine()
{
DateTime date = Convert.ToDateTime(Calendar1.VisibleDate.Date.ToString());
var firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
var lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
string GridDS_FirstLine = "set dateformat dmy Select DutyDate,WeekDay,First, Second from [Duty].[dbo].[Schedule_FirstLine] WHERE DutyDate >= '" + firstDayOfMonth + "' AND DutyDate <= '" + lastDayOfMonth + "'";
dt_FirstLine = new DataTable();
con_FirstLine = new SqlConnection(cs);
con_FirstLine.Open();
adapt_FirstLine = new SqlDataAdapter(GridDS_FirstLine, con_FirstLine);
adapt_FirstLine.Fill(dt_FirstLine);
if (dt_FirstLine.Rows.Count > 0)
{
GridView5.DataSource = dt_FirstLine;
GridView5.DataBind();
}
GridView5.Columns[0].Visible = true;
}
You name the event on the grid like this?
<asp:GridView ID="TaskGridView" runat="server"
AutoGenerateEditButton="True"
AllowPaging="true"
OnRowEditing="TaskGridView_RowEditing"
OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
OnRowUpdating="TaskGridView_RowUpdating"
OnPageIndexChanging="TaskGridView_PageIndexChanging">
</asp:GridView>

Getting textbox's value in Nested gridview

I have a nested gridview, And there is a textbox that named TextBoxDescription to insert user information in the second gridview. But when I want to catch textbox's (TextBoxDescription) value its return Null.
Html Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
DataKeyNames="ReportId" OnRowDataBound="GridView2_OnRowDataBound" ForeColor="#333333">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<ItemStyle Width="35px" HorizontalAlign="Center" />
<ItemTemplate>
<img alt="" style="cursor: pointer" src="plus.png" />
<asp:Panel ID="Panel5" runat="server" Style="display: none; text-align: center;">
<asp:GridView ID="GridView2" border="0" runat="server" DataKeyNames ="ReportId" OnRowCommand="GridView1_RowCommand"
Style="direction: rtl" Width="100%" Height="100%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table width="100%" height="100%" bgcolor="#F4F4F4">
<tr>
</tr>
<tr>
<td style="width: 50%; height: 50%" hidefocus="hidefocus" unselectable="off" valign="top">
<asp:Panel ID="Panel3" runat="server" GroupingText="یاد داشت">
<asp:TextBox ID="TextBoxDescription" runat="server" Style="resize: none; width: 612px;
height: 160px;" Text='<%# Eval("UserDescription") %>' TextMode="MultiLine"></asp:TextBox>
<br />
<br />
<asp:LinkButton ID="LinkButtonSave" CommandName ="updateData" CommandArgument='<%#Eval("ReportId") %>' runat="server">ذخیره</asp:LinkButton>
</asp:Panel>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.
.
.
C# Code:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "updateData")
{
int i = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
TextBox tb = (TextBox)row.FindControl("TextBoxDescription");
string Text = tb.Text;
}
}
Do like below :
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int index = row.RowIndex;
TextBox tb= (TextBox )GridView1.Rows[index].FindControl("TextBoxDescription");
http://forums.asp.net/p/2053658/5919172.aspx?Getting+textbox+s+value+in+Nested+gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Details">
<ItemTemplate>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView2_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table>
<tr>
<td>
<asp:Panel ID="Panel3" runat="server" GroupingText="یاد داشت">
<asp:TextBox ID="TextBoxDescription" runat="server" Style="resize: none; width: 612px; height: 160px;"
Text='<%# Eval("UserDescription") %>' TextMode="MultiLine"></asp:TextBox>
<br />
<br />
<asp:LinkButton ID="LinkButtonSave" CommandName="updateData" CommandArgument='<%#Eval("ReportId") %>' runat="server">ذخیره</asp:LinkButton>
</asp:Panel>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable gdv1source = new DataTable();
gdv1source.Columns.Add("ID");
gdv1source.Rows.Add("1");
GridView1.DataSource = gdv1source;
GridView1.DataBind();
}
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
TextBox tb = (TextBox)row.FindControl("TextBoxDescription");
string Text = tb.Text;
lbltext.Text = "Text Value is: " + Text;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gdv2 = (GridView)e.Row.FindControl("GridView2");
BindGridView2(gdv2);
}
}
private static void BindGridView2(GridView gdv2)
{
DataTable gdv2source = new DataTable();
gdv2source.Columns.Add("UserDescription");
gdv2source.Columns.Add("ReportId");
gdv2source.Rows.Add("UserDescription1", "1");
gdv2source.Rows.Add("UserDescription2", "2");
gdv2.DataSource = gdv2source;
gdv2.DataBind();
}

PostBack from a link in Grid within UpdatePanel

I have a grid and few textboxes within an UpdatePanel. On selecting a paricular row the textboxes are filled using JS. UpdatePanel was introduced as one textbox was filled using a method in the code.
There is also a link in grid row which opens a pop-up(also filled from code behind).
After using UpdatePanel the link is not working(assuming because of no full post back).
I tried using UpdateMode="Conditional" property and registering Link control for PostBAck control.
But still it is not working:
Code
<asp:UpdatePanel ID="Update" runat="server" Up>
<ContentTemplate>
<table width="100%">
<tr>
<td>
<asp:GridView ID="gvSession" BorderColor="#ffcc00" RowStyle-BorderColor="#ffcc00"
AutoGenerateColumns="False" Font-Names="Verdana" DataKeyNames="SessionId" runat="server"
RowStyle-BorderStyle="Solid" RowStyle-BorderWidth="1px" GridLines="Both" Width="100%"
OnRowCreated="gvSession_RowCreated" OnDataBound="gvSession_DataBound">
<RowStyle CssClass="dbGrid_Table_row" />
<HeaderStyle CssClass="dbGrid_Table_Header" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rbSelect" onclick="javascript:CheckOtherIsCheckedByGVIDMore(this);"
runat="server" OnCheckedChanged="rbSelect_CheckedChanged" AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Session Name">
<ItemTemplate>
<asp:Label ID="lblSessionName" Text='<%# Eval("SessionName") %>' runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="16%"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Preview">
<ItemTemplate>
<asp:LinkButton ID="lbPreview" Text="Preview" CommandName="Preview" AutoPostBack="true"
CommandArgument='<%# Eval("SessionId") + ";" + Eval("TrainingTypeName") %>'
runat="server" OnClick="lbPreview_Click"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="10%"></ItemStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<table id="Table2" runat="server" width="100%">
<tr>
<td colspan="2" align="center" style="text-align: center">
<asp:TextBox ID="txtSessionDtl" runat="server" Font-Size="Small" Style="text-align: center"
ForeColor="Black" Wrap="true" Height="20px" Width="95%" BorderStyle="None"></asp:TextBox>
</td>
</tr>
<tr>
<td style="width: 12%">
<asp:Label ID="Label9" CssClass="label" runat="server">Upload File : </asp:Label>
</td>
<td>
<asp:TextBox ID="txtFilePath" Enabled="false" BorderStyle="Solid" BorderColor="Black"
runat="server" Width="741px"></asp:TextBox>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
FOr Link click:
protected void lbPreview_Click(object sender, EventArgs e)
{
try
{
LinkButton link = (LinkButton)sender;
GridViewRow gv = (GridViewRow)(link.Parent.Parent);
LinkButton linkPreview = (LinkButton)gv.FindControl("lbPreview");
string[] arg = new string[2];
arg = linkPreview.CommandArgument.ToString().Split(';');
string strSessionId = arg[0];
string strTrgType = arg[1];
string mailContent = GenerateNominationMailer(strSessionId, strTrgType);
hidMailContent.Value = mailContent;
string mailContent1 = mailContent.Replace(System.Environment.NewLine, "");
string myScript = "<SCRIPT LANGUAGE='javascript'>";
myScript = myScript + " my_window = window.open('', '', 'status=1,width=1000,height=800,scrollbars=yes');";
myScript = myScript + " my_window.document.write(\"" + mailContent1.Replace("\"", "'") + "\");";
myScript = myScript + " my_window.document.close();";
myScript = myScript + " </script>";
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Nomination Mailer", myScript,false);
}
catch (Exception ex)
{
AlnErrorHandler.HandleError(ex);
}
}
For registering control:
protected void gvSession_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow grdrow in gvSession.Rows)
{
LinkButton Preview = (LinkButton)grdrow.FindControl("lbPreview");
ScriptManager current = ScriptManager.GetCurrent(Page);
if (current != null)
current.RegisterPostBackControl(Preview);
}
}
enter code here
set trigger for your event. put this at end of ContentTemplate
<Triggers>
<asp:AsyncPostBackTrigger ControlID="lbPreview" EventName="Click" />
</Triggers>
Replace your old event with this
protected void gvSession_DataBound(object sender, GridViewRowEventArgs e)
{
LinkButton Preview = e.Row.FindControl("lbPreview") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(Preview);
}
and assign gvSession_DataBound event in GridView as DataBound event

page load with child grids taking too much of time in loading the page

I have three grids - Category grid, Items grid and Sub Items Grid. I have category grid (grdCategories) and for each category there are many items which i bind to child grids (grdItems). For every item there are many sub items which i display in sub child grid (grdSubItems). Now the problem is that page takes too much of time in loading the data. My HTML Code is below:
It takes even minutes to load the data:
ASPX
<asp:GridView ID="grdCategories" runat="server" AutoGenerateColumns="false" DataKeyNames="Category"
CssClass="menu_items" OnRowDataBound="grdCategories_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel ID="pnlMealOptionsHeader" runat="server" Width="100%">
<h1>
<a id='<%# Eval("CategoryX")%>'>
<asp:Label ID="lblCategory" runat="server" Text='<%#Eval("Category") %>' Visible="false"></asp:Label>
<asp:Label ID="lblCategoryX" runat="server" Text='<%#Eval("CategoryX") %>'></asp:Label>
</a>
</h1>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMealOptionsBody">
<asp:Label ID="lblCategoryXX" runat="server" CssClass="title_2" Text='<%#Eval("CategoryXX") %>'></asp:Label>
<!--Items in Category -->
<asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="false" CssClass="active-grid"
DataKeyNames="Item" OnRowDataBound="grdItems_RowDataBound" ShowHeader="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item") %>' Visible="false"></asp:Label>
<asp:Label ID="lblItemX" CssClass="title" runat="server" Text='<%#Eval("ItemX") %>'></asp:Label>
<asp:Label ID="lblItemXX" CssClass="title" runat="server" Text='<%#Eval("ItemXX") %>' style=" font-size:smaller; font-weight:normal"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="grdSubItems" runat="server" AutoGenerateColumns="false" CssClass=""
DataKeyNames="SubItem" ShowHeader="false" OnRowDataBound="grdSubItems_RowDataBound">
<HeaderStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item") %>' Visible="false"></asp:Label>
<asp:Label ID="lblSubItem" runat="server" Text='<%#Eval("SubItem") %>' Visible="false"></asp:Label>
<asp:Label ID="lblNoofOptions" runat="server" Text='<%#Eval("NumofOptions") %>' Visible="false"></asp:Label>
<asp:Label ID="lblSubItemX" CssClass="qty" runat="server" Text='<%#Eval("SubItemX") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" CssClass="price" Text='<%#String.Format("£{0}",Eval("SellingCost")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!--End Items in Category -->
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table width="900px">
<tr>
<td align="center">
<h1>
No Data Available</h1>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
Code Behind
Categories Gridview Bind
private void FillCategoriesGrid()
{
DataSet ds = new DataSet();
ShopCategoryMapBL bl = new ShopCategoryMapBL(SessionContext.SystemUser);
bl.FetchForShop(ds, RowId);
grdCategories.DataSource = ds.Tables[0].DefaultView;
grdCategories.DataBind();
}
Items Gridview Bind
protected void grdCategories_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView chkTopings = e.Row.FindControl("grdItems") as GridView;
Label lblCategory = e.Row.FindControl("lblCategory") as Label;
FillItemsGrid(chkTopings, WebHelper.Cast(lblCategory.Text, 0));
}
}
protected void FillItemsGrid(GridView grdItems, int Category)
{
try
{
//int cleanOrder = CargoBag.GetValue("CleanOrder", 0);
DataSet aDataSet = new DataSet();
ItemBL bl = new ItemBL(SessionContext.SystemUser);
bl.FetchForCategory(aDataSet, Category, RowId);
grdItems.DataSource = aDataSet.Tables[0];
grdItems.DataBind();
}
catch (Exception ex) { }
}
Sub Items Gridview Bind
protected void grdItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grdSubItems = e.Row.FindControl("grdSubItems") as GridView;
Label lblItem = e.Row.FindControl("lblItem") as Label;
FillSubItemsGrid(grdSubItems, WebHelper.Cast(lblItem.Text, 0));
}
}
protected void FillSubItemsGrid(GridView grdSubItems, int Item)
{
try
{
//int cleanOrder = CargoBag.GetValue("CleanOrder", 0);
DataSet aDataSet = new DataSet();
SubItemBL bl = new SubItemBL(SessionContext.SystemUser);
bl.FetchForItem(aDataSet, Item);
grdSubItems.DataSource = aDataSet.Tables[0];
grdSubItems.DataBind();
}
catch (Exception ex) { }
}
You need to provide all of your code before we can provide an accurate answer.
For example:
Where SubItemBL is defined?
Also try to see what line is the exact bottleneck.
Is it
bl.FetchForCategory(aDataSet, Category, RowId);
or
grdSubItems.DataBind();
If above line is the bottleneck, note that Gridview binding to a datasource with large number of data is indeedslow. how large is your data?

Categories

Resources