How to highlight a selected row in a gridview? - c#

I am adding a dropdown to gridview using template field as:
<asp:TemplateField HeaderText="Change Color">
<ItemTemplate>
<asp:DropDownList ID="dropdownid" DataSourceID="sqldatasource_id" DataTextField="username"
BackColor="GrayText" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" AppendDataBoundItems="True" runat="server" AutoPostBack="True">
<asp:ListItem Text="--Select One--" Value="" Selected="True" />
</asp:DropDownList>
SqlDataSource is:
<asp:SqlDataSource ID="sqldatasource_id" runat="server" ConnectionString="<%$ ConnectionStrings:crudconnection %>"
SelectCommand="SELECT [username] FROM [crudtable]"></asp:SqlDataSource>
Indexchange-Event is as :
protected void GridView1_SelectedIndexChanged(object sender,EventArgs e)
{
}
I want to highlight a row when any value from the corresponding dropdownlist is selected.
How can i do it?
Thanks in advance.
i tried it:
GridView1.Rows[GridView1.SelectedIndex].BackColor = Color.Red;
But still it is giving a exception as follow when-ever i select any value from any dropdownlist.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
I am getting index number of selected row as already mentioned.can't i increment it from there and can use back-color property too?

Can you give this a try:
GridView1.Rows[GridView1.SelectedIndex].BackColor = Color.Red inside your GridView1_SelectedIndexChanged?
It should set the background color of the selected row to a red color

Try GridView_SelectedIndexChanging(). Here is how:
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//This is current row. Set it to default color
GridView1.SelectedRow.BackColor = System.Drawing.Color.White;
//This is selected row. Set it to color you wish
GridView1.Rows[e.NewSelectedIndex].BackColor = System.Drawing.Color.Black;
}

Its working.I made changes like below.
int abc=row.rowindex+3;
GridView1.Rows[abc].BackColor = Color.Yellow;
Thanks for support.

function ChangeRowColor(row) {
row = parseInt(row) + 1;
if (previousRow == row)
return; //do nothing
else if (previousRow != null) {
document.getElementById("MainContent_gvSimulationManager").rows[previousRow].style.backgroundColor = previouscolor;
}
previouscolor = document.getElementById("MainContent_gvSimulationManager").rows[row].style.backgroundColor;
document.getElementById("MainContent_gvSimulationManager").rows[row].style.backgroundColor = "#888888";
previousRow = row;
//Disable and enable Session
var simulationStatus = document.getElementById("MainContent_gvSimulationManager").rows[row].cells[3].innerText;
EnableAndDisable(simulationStatus);

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="pub_id" HeaderText="pub_id" />
<asp:BoundField DataField="pub_name" HeaderText="pub_name" />
<asp:BoundField DataField="city" HeaderText="city" />
<asp:BoundField DataField="state" HeaderText="state" />
<asp:BoundField DataField="country" HeaderText="country" />
<asp:ButtonField Text="Click" CommandName="Select" ItemStyle-Width="30" />
</Columns>
</asp:GridView>
<br />
<asp:Label ID="msg" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;
string connetionString = "Data Source=.;Initial Catalog=pubs;User ID=sa;Password=*****";
sql = "select * from publishers";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string pName = GridView1.SelectedRow.Cells[1].Text;
grdCList.SelectedRow.Cells[3].ForeColor = System.Drawing.Color.Red;
}

Related

Cannot search on gridview C# aspnet

I'm implementing a search bar to filter GridView1. I followed this tutorial but when it doesnt work. I want to filter the UserID and show only the specific output match the user input. I clicked on search but nothing work, it just refreshed the page and nothing else.
aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Manager.Master" AutoEventWireup="true" CodeBehind="ExceptionReport.aspx.cs" Inherits="Bracelet.ExceptionReport" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-md-10">
<div class="content-box-large">
<div class="panel-heading">
<div class="panel-title">Admin Log Report</div>
</div>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button Text="Search" runat="server"/>
<div class="panel-body">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
</div>
</div>
<asp:LinqDataSource ID="LinqDataSource2" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users">
</asp:LinqDataSource>
<asp:LinqDataSource ID="LinqDataSource1" runat="server" ContextTypeName="Bracelet.BraceletDataContext" EntityTypeName="" TableName="Users" Where="UserRole == #UserRole">
<WhereParameters>
<asp:Parameter DefaultValue="Admin" Name="UserRole" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
</div>
</asp:Content>
Full code .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.Configuration;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace Bracelet
{
public partial class ExceptionReport : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void Search(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT UserID, UserName, UserEmail, logtime FROM [User] WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#UserID ", txtSearch.Text.Trim());
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
}
}
Not too bad.
but, there are few errors and issues.
first up, you have search button - but it has no "id" assigned.
You probably should get in the habit of simple drag + drop the button in from the tool box.
So, we now have this for the button and the grid:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:Button ID="cmdSearch" runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserEmail" HeaderText="UserEmail" SortExpression="UserEmail" />
<asp:BoundField DataField="logtime" HeaderText="logtime" SortExpression="logtime" />
</Columns>
</asp:GridView>
NOTE carefull in above, how we gave the button a "ID"
So, our basic code to load up the grid?
FYI: huge love, hugs, high-5's for checking is-post back!!!
(always, always do that!!!).
So, our code to load things up can thus look like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
this.BindGrid();
}
void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["BraceletConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT UserID, UserName, UserEmail, logtime FROM [User]", con))
{
// optional text box filter (blank = all)
if (txtSearch.Text != "")
{
cmd.CommandText += " WHERE UserID LIKE '%' + #UserID + '%'";
cmd.Parameters.Add("#UserID", SqlDbType.Text).Value = txtSearch.Text;
}
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
Note how we did not need that data adaptor - not needed.
However, we still not created the code stub for the button click (that's why your code is not working - you did not give your button a "id"
So, in the designer - double click on the button. That will create the "event" for you, and jump to the code editor, and we have this:
protected void cmdSearch_Click(object sender, EventArgs e)
{
this.BindGrid();
}
so, in general - don't type in the "event" stubs for a button - double click on the button - it will create + wire it up for you.
Note close, if I flip back to mark-up, the button has become this:
<asp:Button ID="cmdSearch" runat="server" Text="Search" OnClick="cmdSearch_Click" />

unable to update database through gridview in c#

I am creating a system in which i want to edit several records from the database through administrator using a data grid view:
Table Schema used in this is
CREATE TABLE [dbo].[tbl_Employee] (
[ID] INT NOT NULL,
[Name] VARCHAR (50) NULL,
[City] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
I have added Add OnRowEditing, OnRowUpdating and OnRowCancelingEdit events to the GridView.
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="6" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Text='<%#Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:Label ID="lbl_City" runat="server" Text='<%#Eval("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_City" runat="server" Text='<%#Eval("City") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#663300" ForeColor="#ffffff"/>
<RowStyle BackColor="#e7ceb6"/>
</asp:GridView>
</div>
And the c# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
//Connection String from web.config File
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ShowData();
}
}
//ShowData method for Displaying Data in Gridview
protected void ShowData()
{
dt = new DataTable();
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("Select ID,Name,City from tbl_Employee",con);
adapt.Fill(dt);
if(dt.Rows.Count>0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
con.Close();
}
protected void GridView1_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
//NewEditIndex property used to determine the index of the row being edited.
GridView1.EditIndex = e.NewEditIndex;
ShowData();
}
protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.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;
TextBox name = GridView1.Rows[e.RowIndex].FindControl("txt_Name") as TextBox;
TextBox city = GridView1.Rows[e.RowIndex].FindControl("txt_City") as TextBox;
con = new SqlConnection(cs);
con.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update tbl_Employee set Name='"+name.Text+"',City='"+city.Text+"' where ID="+Convert.ToInt32(id.Text),con);
cmd.ExecuteNonQuery();
con.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
ShowData();
}
protected void GridView1_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
ShowData();
}
}
The code is not showing any error but the database is not getting updated.
Where am i going wrong?

Visual Studio 12 - Gridview inserting footer row on submit

I have a gridview that I need a footer row inserted with the data from a textbox when the user hits submit. I have tried over and over and I can not get past the following error:
Object reference not set to an instance of an object. The error is flagged on the Textbox AddName line of code in the code behind.
Here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs" Inherits="WorkOrder.Admin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style.css" rel="stylesheet" type="text/css" />
<link href="msgBoxLight.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.msgBox.js" type="text/javascript"></script>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" Width="1020px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/mast_left.png" />
</asp:Panel>
</div>
<div class="Section"> <hr /><h2>
Online Work Order Form - (Admin)</h2>
</div>
<br />
<asp:Label ID="Label2" runat="server" Text="Select data you want to view and click the submit button:" CssClass="label"></asp:Label><br /><br />
<div>
<asp:GridView ID="GridViewAdmin" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource1" DataKeyNames="WO_ID" EnableModelValidation="True"
>
<Columns>
<asp:BoundField DataField="WO_ID" HeaderText="WO_ID" ReadOnly="True" SortExpression="WO_ID" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:BoundField DataField="Job_Title" HeaderText="Job_Title" ReadOnly="True" SortExpression="Job_Title" />
<asp:BoundField DataField="Job_Assigned_To" HeaderText="Job_Assigned_To" SortExpression="Job_Assigned_To" />
<asp:CheckBoxField DataField="Completed" HeaderText="Completed" SortExpression="Completed" />
<asp:BoundField DataField="Completed_Date" HeaderText="Completed_Date" SortExpression="Completed_Date" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT [WO_ID], [Name], [Job_Type], [Job_UpdateName], [Job_Title], [Job_Description], [Job_Assigned_To], [Completed], [Completed_Date], [Notes] FROM [WO_Submission_Details]"
UpdateCommand="UPDATE [WO_Submission_Details] SET [Job_Assigned_To] = #Job_Assigned_To, [Completed] = #Completed, [Completed_Date] = #Completed_Date, [Notes] = #Notes WHERE [WO_ID] = #WO_ID">
</asp:SqlDataSource>
</div>
<br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AdminReport.aspx">Work Order Report</asp:HyperLink>
<br />
<br />
<hr />
<br />
<asp:Label ID="Label1" runat="server" Text="Enter name below to add to Marketing employee table" CssClass="label"></asp:Label>
<br />
<br />
<asp:Label ID="Label3" runat="server" Text="Name:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox><br /><br />
<asp:Label ID="Label4" runat="server" Text="Email:" CssClass="label"></asp:Label>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
<br /><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<br /><br />
<asp:GridView ID="GridViewStaff" runat="server"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="5"
DataSourceID="SqlDataSource2" datakeynames="ID" AllowSorting="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#Eval("Name") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" text='<%#Eval("Email")%>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>"
SelectCommand="SELECT * FROM [Marketing_Staff]" InsertCommand="INSERT INTO [Marketing_Staff] ([Name], [Email]) VALUES (#Name, #Email)">
<InsertParameters>
<asp:Parameter Type="String" Name="Name"></asp:Parameter>
<asp:Parameter Type="String" Name="Email"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
Code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Design;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Text;
using System.IO;
namespace WorkOrder
{
public partial class Admin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bindgridView();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
TextBox AddName = GridViewStaff.FooterRow.FindControl("txtAddName") as TextBox;
// Response.Write(AddName.Text);
//TextBox Email = GridViewStaff.FooterRow.FindControl("txtAddEmail") as TextBox;
SqlDataSource2.InsertParameters["Name"].DefaultValue = txtAddName.Text;
// SqlDataSource2.InsertParameters["Email"].DefaultValue = txtAddEmail.Text;
SqlDataSource2.Insert();
// ExecuteInsert(txtAddName.Text);
txtAddName.Text = "";
txtAddEmail.Text = "";
}
public string GetConnectionString()
{
//sets the connection string from your web config file "ConnString" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ZSC_WorkOrdersConnectionString"].ConnectionString;
}
public void bindgridView()
{
try
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string query = "Select * WO_ID, Name, Job_Type, Job_UpdateName, Job_Title, Job_Description, Job_Assigned_To, Completed, Completed_Date, Notes FROM WO_Submission_Details";
DataSet ds = new DataSet();
SqlDataAdapter sqldt = new SqlDataAdapter(query, conn);
sqldt.Fill(ds);
GridViewAdmin.DataSource = ds;
GridViewAdmin.DataBind();
if (ViewState["delRows"] != null)
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
//create the javascript array in the client side
//push the deleted row indexes from c# array to javascript array
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("var indexArray = new Array;");
for (int i = 0; i < itemsLength; i++)
{
sb.Append("indexArray.push('" + delIndices[i] + "');");
}
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "arrayScript", sb.ToString());
//call the deleteRow function on the client side
this.ClientScript.RegisterStartupScript(typeof(Page), "del", "javascript:deletegrdvwRow()", true);
}
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewAdmin.EditIndex = e.NewEditIndex;
}
protected void GridViewAdmin_RowCancelingEdit(object sender, EventArgs e)
{
GridViewAdmin.EditIndex = -1;
}
protected void GridViewAdmin_RowCreated(object sender, GridViewRowEventArgs e)
{
foreach (TableCell cell in e.Row.Cells)
{
if (!string.IsNullOrEmpty(cell.Text) && cell.Text != " ")
{
BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
if ((field.DataField != "Job_Assigned_To") && (field.DataField != "Completed") && (field.DataField != "Completed_Date") && (field.DataField != "Notes"))
field.ReadOnly = true;
}
}
}
protected void GridViewAdmin_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GridViewAdmin.PageIndex = e.NewPageIndex;
//while moving to the next page, clear the viewstate
ViewState["delRows"] = null;
}
catch (Exception)
{ }
}
protected void GridViewAdmin_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridViewAdmin.Rows[e.RowIndex];
//i set datakeys="ProductName,ProductID" in gridview in aspx page
//datakeys[rowindex][1]->refers to productid which is primary key.
string WOID = GridViewAdmin.DataKeys[row.RowIndex][0].ToString();
SqlConnection conn = new SqlConnection(GetConnectionString());
TextBox JobAssignedTo = (TextBox)row.FindControl("txtJobAssignedTo");
CheckBox txtCompleted = (CheckBox)row.Cells[1].Controls[0];
TextBox CompletedDate = (TextBox)row.Cells[2].Controls[0];
TextBox Notes = (TextBox)row.Cells[3].Controls[0];
//write your logic here to update the data into the database
conn.Open();
SqlCommand cmd = new SqlCommand("update WO_Submission_Details set Job_Assigned_To='" + JobAssignedTo.Text + "',Completed='" + txtCompleted.Checked + "',Completed_Date='" + CompletedDate.Text + "',Notes='" + Notes.Text + "'where WO_ID='" + WOID + "'", conn);
//SqlCommand cmd = new SqlCommand("update duplicating_request_table set Completed_By=#CompletedBy WHERE Job_No=#JobNo");
cmd.ExecuteNonQuery();
conn.Close();
GridViewAdmin.EditIndex = -1;
//those rows which are deleted previously while updating store it's indexs
if (ViewState["delRows"] == null)
{
int[] delIndices = new int[12];
delIndices[0] = e.RowIndex;
ViewState["delRows"] = delIndices;
}
else
{
int[] delIndices = (int[])ViewState["delRows"];
int itemsLength = delIndices.Count(indx => indx != 0);
delIndices[itemsLength] = e.RowIndex;
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
}
}
}
It looks like your SqlDataSource2 is causing the error. Please double check that both Name and Email are of DB type string in your DB.
In your ASPX SqlDataSource2 make the following changes:
<InsertParameters>
<asp:QueryStringParameter Name="Name" QueryStringField="Name" DbType=String />
<asp:QueryStringParameter Name="Email" QueryStringField="Email" DbType=String />
</InsertParameters>
In your C# Code-Behind, change to this:
SqlDataSource2.InsertParameters[0].DefaultValue = txtAddName.Text;

CheckBox in GridView failing

I've read through about 50 sites and stackoverflow questions that advise to do what I have in my code below. I've been through many variations on this, and I can't seem to get it to do anything at all.
I've been watching SQL Profiler and nothing is sent at all.
I get no errors.
All I want is a list with checkboxes I can click to change a single setting from 0 to 1. I'm sure it's me, but I'm missing it, and I've spent an embarrassingly long time on this. Thanks for any input.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames="npi"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="provcode" HeaderText="provcode"
SortExpression="provcode" />
<asp:BoundField DataField="npi" HeaderText="npi" SortExpression="npi" />
<asp:BoundField DataField="firstname" HeaderText="firstname"
SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname"
SortExpression="lastname" />
<asp:TemplateField HeaderText="Submit Y/N">
<ItemTemplate>
<asp:CheckBox ID="submitChk" runat="server" Enabled="true" AutoPostBack="True" OnCheckChanged="submit_CheckedChanged"
Checked='<%# Bind("submit") %>'/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<p>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DS_SSRS_ReportsConnectionString1 %>"
SelectCommand="SELECT [provcode], [npi], [firstname], [lastname], [submit]
FROM [DRPprovders]
ORDER BY lastname, firstname"
onselecting="SqlDataSource1_Selecting"
>
</asp:SqlDataSource>
</p>
CodeBehind:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
public partial class Pages_ProvSelect : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void submit_CheckedChanged(object sender, EventArgs e)
{
CheckBox submitChk = (CheckBox)sender;
GridViewRow row = (GridViewRow)submitChk.NamingContainer;
//int ID = (int)GridView1.DataKeys[row.DataItemIndex].Value;
String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;
}
}
You just need to connect to the database and perform the update "manually" in that CheckedChanged method.
Something like this should work:
protected void submit_CheckedChanged(object sender, EventArgs e)
{
CheckBox submitChk = (CheckBox)sender;
GridViewRow row = (GridViewRow)submitChk.NamingContainer;
String npi = (String)GridView1.DataKeys[row.DataItemIndex].Value;
SqlConnection conn = new SqlConnection("your connection string here");
string updateQuery = "UPDATE DRPprovders SET submit = #submit WHERE npi = #npi";
SqlCommand cmd = new SqlCommand(updateQuery, conn);
// If it's checked, pass 1, else pass 0
cmd.Parameters.AddWithValue("#submit", submitChk.Checked ? 1 : 0);
cmd.Parameters.AddWithValue("#npi", npi);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
You might just be able to pass the boolean value of submitChk.Checked (rather than converting to 1's and 0's like I did), I can't remember now (and I was just typing this off the top of my head, so it's untested).

how to update only child GridView?

here is what I'm doing right now:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridViewUserScraps_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" Text="Comment" runat="server" CommandName="Comment" CommandArgument='<%#Eval("ScrapId")%>' />
<asp:GridView ID="GridView2" runat="server">
<%--this GridView2 showing comments--%>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridViewUserScraps_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridView gv = new GridView();
gv = (GridView)row.FindControl("GridView2");
//getting data to bind child gridview.
gv.DataSource = td;
gv.DataBind();
}
so, on button click of the GridView1 I'm updating database and fetching data at same time, there is no any problem in that. But for this I have to Bind/refresh parent(GridView1) Gridview which quite slow process as there are almost 50 rows. what I'm looking is; I want to update or refresh only GridView2 to be shown added comments.
The GridView1.RowCommand is the right event to handle the button's action.
GridView1.RowCommand += (o, e) =>
{
var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
var makeComments = row.FindControl("MakeComments") as TextBox;
int scrapId = Int32.TryParse((string)e.CommandArgument, out scrapId) ? scrapId : 0;
var gridView2 = row.FindControl("GridView2") as GridView;
... place here the code which the comments
gridView2.DataSource = GetCommentsByScrapId();
gridView2.DataBind();
};
On this event (or others), the parent won't bind, unless you specify it.
One common reason the bind a control is by mistakenly call DataBind() every time when the page loads. To prevent this, it is needed to do the binding on the first request of the page and the proper way is to check if the IsPostBack is false.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = GetUserScraps();
GridView1.DataBind();
}
}
You can refresh only the child gridview without refreshing your parent gridview.
To do it you can do a client side click (ClientClick) to the button and call a jquery function, instead of a server side click.
Then you can update only the items in your child gridview, by calling a web method or http handler class from the particular jquery function via ajax call.
Here your parent grid won't be refreshed since there is no server hit at the button click.
Hope this helps and if you need I will provide sample code for the jquery function.
Try this
foreach(GridViewRow rIndex in GridView1.Rows)
{
GridView gv = new GridView();
gv = (GridView)row.FindControl("GridView2");
//getting data to bind child gridview.
// if you want to get the row key value use GridView1.DataKeys[rIndex.RowIndex].Value
gv.DataSource = td;
gv.DataBind();
}
I would set the commandname of the button then use the gridview's OnRowCommand event
<asp:gridview id="GridView1" runat="server" onrowdatabound="GridViewUserScraps_RowDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" Text="Comment" runat="server" CommandName="UpdateChildGrid" />
<asp:GridView ID="GridView2" runat="server">
<%--this GridView2 showing comments--%>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Code Behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="UpdateChildGrid")
{
GridViewRow row = (e.CommandSource as Button).NamingContainer as GridViewRow;
GridView child = row.FindControl("GridView2") as GridView;
// update child grid
}
}
Doing this from memory so it may not be exact, but should be close enough to give you an idea of where to go
GridView HTML
<asp:gridview id="GridView1" runat="server" onrowdatabound="GridViewUserScraps_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" Text="Comment" runat="server" OnClick="btnPost_Click" />
<asp:GridView ID="GridView2" runat="server">
<%--this GridView2 showing comments--%>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Code Behind
protected void btnPost(object sender, EventArgs e)
{
//Your code for other operations
//
GridView GridView2 = (GridView)((GridViewRow)((Button)sender).NamingContainer).FindControl("GridView2");
GridView2.DataSource = YourDataBasefetchingFunction();
GridView2.DataBind()
}
Note - Convert the ScrapID DataItem into the DataKey
To Update /refresh only the Child GridView2 in the row where the Update button has been clicked
First of all U need to place the entire GridView1 in Update Panel.
And the child GridView inside another UpdatePanel
Then on the button click U just hav to save ur data and refresh the child grid , in this way only the child grid will be refreshed.
heres a working example.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
SqlCommand cmd = new SqlCommand("select top 10 * from orders", conn);
cmd.Connection.Open();
var dt = cmd.ExecuteReader();
GridView1.DataSource = dt;
GridView1.DataBind();
cmd.Connection.Close();
cmd.Dispose();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateChildGrid")
{
GridViewRow row = (e.CommandSource as Button).NamingContainer as GridViewRow;
GridView child = row.FindControl("GridView2") as GridView;
string id = row.Cells[0].Text;
SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
SqlCommand cmd = new SqlCommand("select top 5 * from [order Details] where OrderID = " + id, conn);
cmd.Connection.Open();
var dt = cmd.ExecuteReader();
child.DataSource = dt;
child.DataBind();
cmd.Connection.Close();
cmd.Dispose();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string id = e.Row.Cells[0].Text;
GridView gv = new GridView();
gv = (GridView)e.Row.FindControl("GridView2");
SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
SqlCommand cmd = new SqlCommand("select top 5 * from [order Details] where OrderID = " + id, conn);
cmd.Connection.Open();
var dt = cmd.ExecuteReader();
gv.DataSource = dt;
gv.DataBind();
cmd.Connection.Close();
cmd.Dispose();
}
}
}
}
And code behind
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<p>
To learn more about ASP.NET visit www.asp.net.
</p>
<p>
You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409"
title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
onselectedindexchanged="GridView1_SelectedIndexChanged"
AutoGenerateColumns="False"
onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="OrderID" />
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
<asp:Button ID="btnPost" ButtonType="Button" Text="Comment" runat="server" CommandName="UpdateChildGrid" />
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>

Categories

Resources