Button event in GridView not responding. C# - c#

I have a problem with my buttons in the grid view. It is not responding to my Response.Redirect("secondHistory.aspx") and my Console.WriteLine("hih"). Here is the HTML code
<asp:GridView runat="server" AutoGenerateColumns="false" ID="GridView1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowCommand="GridView_RowCommand" Width="1027px">
<Columns>
<asp:BoundField DataField="ExcelID" HeaderText="Excel ID" />
<asp:BoundField DataField="excelName" HeaderText="Excel Name" />
<asp:BoundField DataField="excelDescription" HeaderText="Excel Description" />
<asp:BoundField DataField="date / time" HeaderText="Date / Time" />
<asp:BoundField DataField="empID" HeaderText="Employee ID" />
<asp:BoundField DataField="empName" HeaderText="Employee Name" />
<asp:BoundField DataField="engID" HeaderText="Engineer ID" />
<asp:BoundField DataField="engName" HeaderText="Engineer Name" />
<asp:BoundField DataField="firstApproval" HeaderText="First Approval(Engineer)" />
<asp:TemplateField HeaderText="Second Approval (Manager)">
<ItemTemplate>
<asp:Button ID="acceptBtn" runat="server"
CommandName="Accept"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
Text="Accept" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is the backend code of the button.
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Accept")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
Console.WriteLine("hih");
Response.Redirect("secondHistory.aspx");
}
}
Here is the code to populate the table if its necessary.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ExcelID", typeof(int));
dt.Columns.Add("excelName", typeof(string));
dt.Columns.Add("excelDescription", typeof(string));
dt.Columns.Add("date / time", typeof(string));
dt.Columns.Add("empID", typeof(int));
dt.Columns.Add("empName", typeof(string));
dt.Columns.Add("engID", typeof(int));
dt.Columns.Add("engName", typeof(string));
dt.Columns.Add("firstApproval", typeof(string));
dt.Columns.Add("secondApproval", typeof(string));
for(int i = 0; i < textfiles.Length; i++)
{
textList.Add(File.ReadAllText(textfiles[i]));
}
string[] textArray = textList.ToArray();
for (int i = 0; i < excelfiles.Length; i++)
{
dt.Rows.Add(i, excelfiles[i], textArray[i] , File.GetCreationTime(textfiles[i]), 837482, "*empName*", 917378, "*engName*", "Approved");
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
Please help thanks!

Related

How do I add multiple hyperlinks to a table cell from a list in the datasource?

I need to add multiple hyperlinks to the table cell in radgrid so users can click the link to redirect them to another page. The datasource of the grid is a domain which contains a list of links for each customer.
public class CustomerOverviewDomain
{
public CustomerEntity Entity { get; set; }
public IEnumerable<LeadDomain> Leads { get; set; }
public IEnumerable<QualifiedLeadsDomain> QualifiedLeads { get; set; }
public IEnumerable<ProspectDomain> Prospects { get; set; }
public List<string> Links
{
get
{
//NavigateUrl = '<%# "~/Reporting/SalesProposal/ProposalDownload.aspx?proposalId="+Eval("entity.ProposalId") %>' >
List<string> Links = new List<string>();
foreach (LeadDomain lead in Leads)
{
string link = "~/LeadsManagement/Leads/LeadsDetail.aspx?leadId=" + lead.entity.LeadId;
Links.Add(link);
}
foreach (QualifiedLeadsDomain qlead in QualifiedLeads)
{
string link = "!/LeadsManagement/QualifiedLeads/QualifiedLeadDetailPage.aspx?qualifiedLeadId=" + qlead.Entity.QualifiedLeadId;
}
foreach (ProspectDomain prospect in Prospects)
{
string link = "~/Prospects/ProspectDetailPage.aspx?prospectId=" + prospect.entity.ProspectMasterId;
Links.Add(link);
}
return Links;
}
}
}
I am unsure of what should be the column in the radgrid and how the data should be databound.
<%--<telerik:GridBoundColumn HeaderText="Links"
DataField="Links" SortExpression="Links" UniqueName="Links"
ShowFilterIcon="false" CurrentFilterFunction="Contains" AutoPostBackOnFilter="false" FilterDelay="500">
<HeaderStyle Width="120px" />
</telerik:GridBoundColumn>--%>
<telerik:GridHyperLinkColumn DataTextField="Links" DataNavigateUrlFields="Links" UniqueName="Links">
</telerik:GridHyperLinkColumn>
<%-- <telerik:GridTemplateColumn
UniqueName="Links"
AllowFiltering="false"
HeaderText="URL">
<ItemTemplate>
<asp:HyperLink ID="Link" runat="server"></asp:HyperLink>
</ItemTemplate>
</telerik:GridTemplateColumn>--%>
I'm guessing something has to be done in the databound event but not sure what exactly. I'm stuck here. Most I could get is a hyperlink "System.Collections.Generic.List`1[System.String]" which links nowhere. Could someone point me in the right direction?
protected void rgCustomer_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
//Get the row from the grid.
GridDataItem item = e.Item as GridDataItem;
if (item != null)
{
List<string> links = item["Links"].;
//GridTableCell linkCell = (GridTableCell)item["Links"];
//var Link = item["Links"];
//if (Link != null)
//{
// TableCell cell = item["Links"];
// if (cell != null)
// {
// }
//}
}
}
//// GridTableCell linkCell = (GridTableCell)item["TemplateLinkColumn"];
// HyperLink reportLink = (HyperLink)reportLinkCell.FindControl("Link");
// // Set the text to the quote number
// reportLink.Text = "Google";
// //Set the URL
// reportLink.NavigateUrl = "http://www.google.com";
// //Tell it to open in a new window
// reportLink.Target = "_new";
}
What you basically need is a nested Grid in a template column. The way i have dealt with this is to nest a radgrid in a template column and on the ItemDataBound event of the parent row, find the nested radGrid and the DataKeyName. I then use the datakey value to pull the data for the current row and bind the data to the nested RadGrid.
ASPX:
<telerik:RadGrid ID="RadGrid3" runat="server" OnNeedDataSource="RadGrid3_NeedDataSource" AutoGenerateColumns="false" OnItemDataBound="RadGrid3_ItemDataBound">
<MasterTableView DataKeyNames="ID">
<Columns>
<%-- Other columns --%>
<telerik:GridBoundColumn UniqueName="Id" DataField="ID" HeaderText="ID"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Name" DataField="Name" HeaderText="Name"></telerik:GridBoundColumn>
<%-- Column with nested template --%>
<telerik:GridTemplateColumn UniqueName="Links" HeaderText="Links">
<ItemTemplate>
<telerik:RadGrid ID="RadGrid4" runat="server" Skin="Windows7" RenderMode="Lightweight">
<MasterTableView DataKeyNames="Id" AutoGenerateColumns="False" ShowHeader="false">
<Columns>
<%-- I have included an id and name column for demo purposes. they can be removed so only the link is displayed --%>
<telerik:GridBoundColumn DataField="ID" ReadOnly="True" HeaderText="Id" SortExpression="Id" UniqueName="Id" DataType="System.Int32" FilterControlAltText="Filter Id column"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Name" ReadOnly="True" HeaderText="Name" SortExpression="Name" UniqueName="Name" DataType="System.Int32" FilterControlAltText="Filter Name column"></telerik:GridBoundColumn>
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Link" DataTextField="Link" HeaderText="Link" SortExpression="Link" UniqueName="Link" FilterControlAltText="Filter Link column"></telerik:GridHyperLinkColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
C#:
protected void RadGrid3_NeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
//Populate parent table with temp data
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
for (int i = 1; i <= 20; i++) {
table.Rows.Add(i, "Name" + i.ToString());
}
RadGrid3.DataSource = table;
}
protected void RadGrid3_ItemDataBound(object sender, GridItemEventArgs e)
{
//If its a row item
if (e.Item.ItemType == GridItemType.Item | e.Item.ItemType == GridItemType.AlternatingItem) {
dynamic item = (GridDataItem)e.Item;
//Find the nested Radgrid in the row
RadGrid subGrid = (RadGrid)item("Links").FindControl("RadGrid4");
//Get the current row's datakey value
int currentRowDataKeyValue = item.GetDataKeyValue("ID");
//Create temp data for nested radgrid
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
table.Columns.Add("Link");
for (int i = 1; i <= 5; i++) {
table.Rows.Add(i, "Row " + currentRowDataKeyValue.ToString + ": Link " + i.ToString, "https://www.google.com");
}
//Set datasource for nested radgrid. This is where you would databind the list of strings from your domain. You will probably need to manipulate the data returned to match the nested grid structure if you want additional columns
subGrid.DataSource = table;
subGrid.DataBind();
}
Alternatively, you can add the links to the DetailTemplateColumn. This is pretty much the same solution, but it displays the nested RadGrid underneath the row instead of in a template column.
ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource" AutoGenerateColumns="false" OnItemDataBound="RadGrid1_ItemDataBound1">
<MasterTableView DataKeyNames="ID">
<Columns>
<telerik:GridBoundColumn UniqueName="Id" DataField="ID" HeaderText="ID"></telerik:GridBoundColumn>
<telerik:GridBoundColumn UniqueName="Name" DataField="Name" HeaderText="Name"></telerik:GridBoundColumn>
</Columns>
<DetailItemTemplate>
<telerik:RadGrid ID="RadGrid2" runat="server" Skin="Windows7" RenderMode="Lightweight">
<MasterTableView DataKeyNames="Id" AutoGenerateColumns="False" ShowHeader="false">
<Columns>
<telerik:GridBoundColumn DataField="ID" ReadOnly="True" HeaderText="Id" SortExpression="Id" UniqueName="Id" DataType="System.Int32" FilterControlAltText="Filter Id column"></telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Name" ReadOnly="True" HeaderText="Name" SortExpression="Name" UniqueName="Name" DataType="System.Int32" FilterControlAltText="Filter Name column"></telerik:GridBoundColumn>
<telerik:GridHyperLinkColumn DataNavigateUrlFields="Link" DataTextField="Link" HeaderText="Link" SortExpression="Link" UniqueName="Link" FilterControlAltText="Filter Link column"></telerik:GridHyperLinkColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</DetailItemTemplate>
</MasterTableView>
</telerik:RadGrid>
C#
protected void RadGrid1_NeedDataSource(object sender,
GridNeedDataSourceEventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
for (int i = 1; i <= 20; i++) {
table.Rows.Add(i, "Name" + i.ToString());
}
RadGrid1.DataSource = table;
}
protected void RadGrid1_ItemDataBound1(object sender, GridItemEventArgs e)
{
if (e.Item.ItemType == GridItemType.Item | e.Item.ItemType == GridItemType.AlternatingItem) {
dynamic item = (GridDataItem)e.Item;
//Find the grid in the DetailTemplate Cell
RadGrid subGrid = (RadGrid)item.DetailTemplateItemDataCell.FindControl("RadGrid2");
// Get the current row datakey value
int currentRowDataKeyValue = Convert.ToInt32(item.GetDataKeyValue("ID"));
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name");
table.Columns.Add("Link");
for (int i = 1; i <= 5; i++) {
table.Rows.Add(i, "Row " + currentRowDataKeyValue.ToString + ": Link " + i.ToString, "https://www.google.com");
}
subGrid.DataSource = table;
subGrid.DataBind();
}
}

what is the command of select in grid view asp.net

I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}

edit only specific fields in gridview using edit template

i am having an error : Object reference not set to an instance of an object. and the red text is:
dt.Rows[row.RowIndex]["Name"] = Name;
i want to edit data in my gridview. here is my code:
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string Name = (row.Cells[0].Controls[0] as TextBox).Text;
string Price = (row.Cells[2].Controls[0] as TextBox).Text;
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[row.RowIndex]["Name"] = Name;
dt.Rows[row.RowIndex]["Price"] = Price;
ViewState["dt"] = dt;
gdview.EditIndex = -1;
this.GetProducts(0);
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
gdview.EditIndex = e.NewEditIndex;
this.GetProducts(0);
}
here is the getproducts()
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = k.GetAllProducts();
gdview.DataBind();
}
what am i missing here?
Another question. When i click on the update link, it shows the edit textbox on the Name, and Price fields. But the value on the name is not there? here is a screenshot.
here is my html code:
<Columns>
<asp:BoundField HeaderText="Name" DataField="Name" SortExpression="Name">
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="ProductCategory " ReadOnly="true" DataField="CategoryName" SortExpression="CategoryNaame" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="Price" DataField="Price" SortExpression="Price" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:ImageField HeaderText ="ImageUrl" DataImageUrlField="ImageUrl" SortExpression="ImageUrl" ReadOnly="true" ControlStyle-Width ="10">
<ControlStyle Width="50px"></ControlStyle>
</asp:ImageField>
<asp:BoundField HeaderText="ProductQuantity" DataField="ProductQuantity" ReadOnly="true" SortExpression="ProductQuantity" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="ProductSold" DataField="ProductSold" SortExpression="ProductSold" ReadOnly="true" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:BoundField HeaderText="AvailableStock" DataField="AvailableStock" SortExpression="AvailableStock " ReadOnly="true" >
<ItemStyle Height="20px" Width="150px" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton2" Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton ID="LinkButton3" Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
First you have to assign the datatable to ur viewstate. then you can able to update the value of the field.
FYI, I have bind the gridview by sqldatasource object.
Please check the code with this
if (!Page.IsPostBack)
{
try
{
gdview.DataSource = SqlDataSource1;
gdview.DataBind();
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataTable dt = new DataTable();
dt = dv.ToTable();
ViewState["dt"] = dt;
}
catch(Exception ex)
{
}
}
-----------------your other method
private void GetProducts(int CategoryID)
{
ShoppingCart k = new ShoppingCart()
{
CategoryID = CategoryID
};
gdview.DataSource = null;
gdview.DataSource = ViewState["dt"];
gdview.DataBind();
}

How to Add a discrete row to gridview

I am binding the gridview and showing their corresponding total in footer without any error. Now I want to add extra runs as below highlighted in image(which is completely discrete datarow and it does not belong to dataset).I want to achieve functionality like below Image.
Here is my code :
<asp:GridView ID="gvFirstInningBatting" runat="server" AllowSorting="True" AutoGenerateColumns="false"
GridLines="None" AllowPaging="false" CellPadding="4" CssClass="GridViewStyle" OnRowDataBound="gvFirstInningBatting_RowDataBound"
ShowFooter="true" ShowHeader="true" Width="100%">
<Columns>
<asp:BoundField DataField="P_PlayerPopulerName" HeaderText="Batting" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" />
<asp:BoundField DataField="SBTS_PlayerStatus" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Left" ItemStyle-Width="20%" />
<asp:BoundField DataField="SBTS_RunsScored" HeaderText="R" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_MinutesBatted" HeaderText="M" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_BallsPlayed" HeaderText="B" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_Fours" HeaderText="4s" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_Sixes" HeaderText="6s" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
<asp:BoundField DataField="SBTS_StrikeRate" HeaderText="SR" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center" ItemStyle-Width="10%" />
</Columns>
</asp:GridView>
In C#
protected void BindGridView(int scheduleId)
{
SqlConnection dBConnection = null;
try
{
dBConnection = new SqlConnection();
dBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["***"].ConnectionString;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("SP_NAME", dBConnection);
cmd.CommandType = CommandType.StoredProcedure;
dBConnection.Open();
DataSet ds = new DataSet();
DataTable dtBatting = new DataTable();
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(ds);
int gvBattingCount = Convert.ToInt32(cmd.Parameters["#BattingRowsCount"].Value);
for (int i = 0; i < gvBattingCount; i++)
{
if (ds.Tables[i].Rows.Count > 0)
{
if (i == 0)
{
DataRow dr1st;
ds.Tables[i].DefaultView.RowFilter = "SBTS_PlayerIsBatted = 1";
dtBatting = ds.Tables[i].DefaultView.ToTable();
dr1st = dtBatting.NewRow();
dr1st["P_PlayerPopulerName"] = " ";
dr1st["SBTS_RunsScored"] = 36;
dr1st["SBTS_PlayerStatus"] = "Extras";
dr1st["SBTS_MinutesBatted"] = 0;
dr1st["SBTS_BallsPlayed"] = 0;
dr1st["SBTS_Fours"] = 0;
dr1st["SBTS_Sixes"] = 0;
dr1st["SBTS_StrikeRate"] = 0;
dtBatting.Rows.Add(dr1st);
gvFirstInningBatting.DataSource = dtBatting;
gvFirstInningBatting.DataBind();
}
}
}
}
the grid is working if I use dr1st["SBTS_Sixes"] = 0; but it shows 0 in the row and if I use dr1st["SBTS_Sixes"] = DBNull.Value; then it is throwing error
Object cannot be cast from DBNull to other types.
What should I do, Please help me out.

edit row in gridview

I would like to help me with my code. I have 2 gridviews. In the first gridview the user can choose with a checkbox every row he wants. These rows are transfered in the second gridview. All these my code does them well.Now, I want to edit the quantity column in second gridview to change the value but i don't know what i must write in edit box.
Here is my code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
public partial class ShowLand : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindPrimaryGrid()
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string query = "select * from Land";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gridview2.DataSource = dt;
gridview2.DataBind();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords1"] != null)
dt = (DataTable)ViewState["SelectedRecords1"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gridview2.HeaderRow
.Cells[0].FindControl("chkAll");
for (int i = 0; i < gridview2.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
CheckBox chk = (CheckBox)gridview2.Rows[i]
.Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gridview2.Rows[i], dt);
}
else
{
dt = RemoveRow(gridview2.Rows[i], dt);
}
}
}
ViewState["SelectedRecords1"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gridview2.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords1"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
for (int i = 0; i < gridview2.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gridview2.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("id = '" + gridview2.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("name");
dt.Columns.Add("price");
dt.Columns.Add("quantity");
dt.Columns.Add("total");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["id"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["name"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["price"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["quantity"] = gvRow.Cells[4].Text;
dt.Rows[dt.Rows.Count - 1]["total"] = gvRow.Cells[5].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("id = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords1"];
gridview3.DataSource = dt;
gridview3.DataBind();
}
}
and the source code is
<asp:GridView ID="gridview2" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource5">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False"
ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name"
SortExpression="name" />
<asp:BoundField DataField="price" HeaderText="price" SortExpression="price" />
<asp:BoundField DataField="quantity" HeaderText="quantity"
SortExpression="quantity" />
<asp:BoundField DataField="total" HeaderText="total" SortExpression="total" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource5" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Land]"></asp:SqlDataSource>
<br />
</div>
<div>
<asp:GridView ID="gridview3" runat="server"
AutoGenerateColumns = "False" DataKeyNames="id"
EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField = "id" HeaderText = "id" />
<asp:BoundField DataField = "name" HeaderText = "name" ReadOnly="True" />
<asp:BoundField DataField = "price" HeaderText = "price"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:TemplateField HeaderText="quantity">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("quantity")%>'</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("quantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "total" HeaderText = "total"
DataFormatString="{0:c}" ReadOnly="True" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:Label ID="totalLabel" runat="server"></asp:Label>
<br />
</div>
</form>
</body>
</html>
This is not particular asp.net solution but that's how I do something like this in my Windows app.
First of all you shoul make shure that there's a selected row in your GridView (gridView.SelectedRow != null). DataTable object allows you to get access to desired row by accessing it not by numeric index but by DataRow-type object index. After getting a reference to the row which fields' value you want to modify just go ahead with changes.
Here's the example:
if (gridView.SelectedRow != null)
{
dataTable.Rows[gridView.SelectedRow].BeginEdit();
dataTable.Rows[gridView.SelectedRow]["yourFieldName"] = newValue;
dataTable.Rows[gridView.SelectedRow].EndEdit();
gridView.DataSource = dataTable;
}
Hope my answer is of any help because I've never dealt with asp.net before.

Categories