I want to bind only Table Columns to CheckBoxList and then the selected columns should be displayed in a GridView.
My code so far is:
public void BindCheckBoxList(DataSet ds)
{
int i = 0;
foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListItem li = new ListItem(dc.ToString(), i.ToString());
CheckBoxList1.Items.Add(li); i++;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
in aspx.cs code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate))
{
if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
{
CheckBox selectCheckbox = new CheckBox();
//Give id to check box whatever you like to
selectCheckbox.ID = "newSelectCheckbox";
e.Row.Cells[1].Controls.Add(selectCheckbox);
}
}
}
i think you use this code.
Here a complete example to hide GridView Columns based on a CheckBoxList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
And on the .aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
Note that AutoGenerateColumns is set to false. If they are auto-generated the columns are not part of the GridView Columns Collection.
And of course HeaderText="xxx" must match the column names from the database that are stored in the DataTable.
Related
Please find image. Here's my whole code, I wanted save each row on save button click. I'm able to get value from cell 0 and cell 1 but unable to get value from cell 2 , where I have drop down list selected value.I'm getting default value "Ignore" instead of selected item. So how do I get selected value of drop down list ?
<div>
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns = "False"
OnRowDataBound = "OnRowDataBound" Width="544px">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:TemplateField HeaderText = "Mapping" >
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" style="font-size: medium; font-family: Cambria" Width="300px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button2" runat="server" Text="Save"
style="font-size: medium; font-family: Cambria" BorderStyle="Groove"
height="32px" Width="116px" onclick="Save_Click" />
</div>
private void BindGrid()
{
DataTable dt = new DataTable();
connection();
cmd = new SqlCommand("Select top 0 * from F3_BC_Product_Mapping_Data", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
ds = new DataSet();
adapter.Fill(ds, "mytable");
int j = 1;
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)) });
foreach (DataColumn column in ds.Tables[0].Columns)
{
dt.Rows.Add(j,column.ColumnName);
j++;
}
GridView2.DataSource = dt;
GridView2.DataBind();
con.Close();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlMap = (e.Row.FindControl("DropDownList1") as DropDownList);
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
for (int i = 0; i < dt.Columns.Count; i++)
{
ddlMap.Items.Add(dt.Columns[i].Caption.ToString());
}
ddlMap.Items.Insert(0, new ListItem("Ignore"));
}
}
protected void Save_Click(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
string cell_1_Value = GridView2.Rows[gr.RowIndex].Cells[0].Text;
string cell_2_Value = GridView2.Rows[gr.RowIndex].Cells[1].Text;
string cell_3_Value = ((DropDownList)gr.FindControl("DropDownList1")).SelectedItem.Value;
}
}
If you are getting default value then you must see binding code. I think you haven't use if(!Page.IsPostBack) before binding and setting default value in drop down. Try to change OnRowDataBound as below.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && !Page.IsPostBack)
{
DropDownList ddlMap = (e.Row.FindControl("DropDownList1") as DropDownList);
DataTable dt = new DataTable();
dt = (DataTable)Session["data"];
for (int i = 0; i < dt.Columns.Count; i++)
{
ddlMap.Items.Add(dt.Columns[i].Caption.ToString());
}
ddlMap.Items.Insert(0, new ListItem("Ignore"));
}
}
I am using radio button inside gridivew. I want to select 1 radio button at a time not multiple. I tried this but not working i.e it disables the only selected one too.
protected void btnAward_CheckedChanged(object sender, EventArgs e)
{
try
{
foreach (GridViewRow gr in gvAppliedWorks.Rows)
{
int RowIndex = gr.RowIndex;
int AppliedWorkID = gvAppliedWorks.DataKeys[gr.RowIndex].Value.ToInt32();
RadioButton rdbtn = gr.FindControl("btnAward") as RadioButton;
if (rdbtn.Checked == true)
{
//if(RowIndex )
rdbtn.Checked = false;
}
}
}
catch (Exception ex)
{
Utility.Msg_Error(Master, ex.Message);
}
}
}
Try this code:
GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton runat="server" id="rbtn1" name="rbtn" GroupName="rgrp" onclick = "RadioCheck(this);" ></asp:RadioButton>
<asp:HiddenField ID="HiddenField1" runat="server" Value = '<%#Eval("ID")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code for filling gridview from DB
protected void bind()
{
using (SqlConnection con = new SqlConnection("Connection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tableName", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
Finally add this script to avoid multiple selection
<script type = "text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=GridView1.ID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
Here is my aspx page, describing a dynamic gridview:
<asp:gridview ID="Gridview1" runat="server" ShowFooter="True"
AutoGenerateColumns="False"
OnRowCreated="Gridview1_RowCreated" style="margin-left: 13px; margin-right: 6px; margin-top: 12px;" Width="1035px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="#" />
<asp:TemplateField HeaderText="Disease">
<ItemTemplate>
<asp:Button ID="Icd" runat="server" Text="ICD 10" Height="23px" Width="69px" OnClick="Icd_Click" />
<asp:TextBox ID="TextBox1" runat="server" Height="23px" Width="301px" MaxLength="100"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="gvCell"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Height="23px" Width="95px" MaxLength="4"></asp:TextBox>
</ItemTemplate>
<ItemStyle CssClass="gvCell"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Stuation">
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
AppendDataBoundItems="true" Height="23px">
<asp:ListItem Value="-1">--Επιλέξτε--</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Therapy">
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Height="23px" Width="223px" MaxLength="100"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="+Add new row"
onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle CssClass="gvCell"></ItemStyle>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
onclick="LinkButton1_Click">Delete row</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#006466" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
And here is the aspx.cs code:
private ArrayList GetDummyData()
{
ArrayList arr = new ArrayList();
arr.Add(new ListItem("Πάσχει", "1"));
arr.Add(new ListItem("Έπασχε", "2"));
return arr;
}
private void FillDropDownList(DropDownList ddl)
{
ArrayList arr = GetDummyData();
foreach (ListItem item in arr)
{
ddl.Items.Add(item);
}
}
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column2", typeof(string)));//for TextBox value
dt.Columns.Add(new DataColumn("Column3", typeof(string)));//for DropDownList selected item
dt.Columns.Add(new DataColumn("Column4", typeof(string)));//for TextBox value
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column4"] = string.Empty;
dt.Rows.Add(dr);
//Store the DataTable in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Bind the Gridview
Gridview1.DataSource = dt;
Gridview1.DataBind();
//After binding the gridview, we can then extract and fill the DropDownList with Data
DropDownList ddl1 = (DropDownList)Gridview1.Rows[0].Cells[3].FindControl("DropDownList1");
FillDropDownList(ddl1);
}
private void AddNewRowToGrid()
{
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState for future reference
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 0; i < dtCurrentTable.Rows.Count - 1; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("TextBox3");
dtCurrentTable.Rows[i]["Column1"] = box1.Text;
dtCurrentTable.Rows[i]["Column2"] = box2.Text;
dtCurrentTable.Rows[i]["Column4"] = box3.Text;
//extract the DropDownList Selected Items
DropDownList ddl1 = (DropDownList)Gridview1.Rows[i].Cells[3].FindControl("DropDownList1");
// Update the DataRow with the DDL Selected Items
dtCurrentTable.Rows[i]["Column3"] = ddl1.SelectedItem.Text;
}
//Rebind the Grid with the current data to reflect changes
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("TextBox3");
//Fill the DropDownList with Data
FillDropDownList(ddl1);
if (i < dt.Rows.Count - 1)
{
//Assign the value from DataTable to the TextBox
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
//Set the Previous Selected Items on Each DropDownList on Postbacks
ddl1.ClearSelection();
ddl1.Items.FindByText(dt.Rows[i]["Column3"].ToString()).Selected = true;
box3.Text = dt.Rows[i]["Column4"].ToString();
}
rowIndex++;
}
}
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void Gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
LinkButton lb = (LinkButton)e.Row.FindControl("LinkButton1");
if (lb != null)
{
if (dt.Rows.Count > 1)
{
if (e.Row.RowIndex == dt.Rows.Count - 1)
{
lb.Visible = false;
}
}
else
{
lb.Visible = false;
}
}
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gvRow = (GridViewRow)lb.NamingContainer;
int rowID = gvRow.RowIndex;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 1)
{
if (gvRow.RowIndex < dt.Rows.Count - 1)
{
//Remove the Selected Row data and reset row number
dt.Rows.Remove(dt.Rows[rowID]);
ResetRowID(dt);
}
}
//Store the current data in ViewState for future reference
ViewState["CurrentTable"] = dt;
//Re bind the GridView for the updated data
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void ResetRowID(DataTable dt)
{
int rowNumber = 1;
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
row[0] = rowNumber;
rowNumber++;
}
}
}
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
}
private void InsertRecords(StringCollection sc)
{
if (Session["pa_id"] != null)
{
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
const string sqlStatement = "INSERT INTO P_deasease (Date,P_Id,Nosos,Situ,Year_d,Therapy) VALUES";
int id = Convert.ToInt32(Session["pa_id"]);
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}(#Date, #p_id ,N'{1}',N'{2}',N'{3}',N'{4}'); ", sqlStatement, splitItems[0], splitItems[1], splitItems[2], splitItems[3]);
}
}
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(sb.ToString(), connection))
{
cmd.Parameters.AddWithValue("#p_id", id);
cmd.Parameters.AddWithValue("#Date", DateTime.Now.ToShortDateString());
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "Success!";
}
else
{
lblid1.Visible = true;
}
}
protected void BtnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
DropDownList ddl1 = (DropDownList)Gridview1.Rows[rowIndex].Cells[3].FindControl("DropDownList1");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
//add them to the collections with a comma "," as the delimited values
sc.Add(string.Format("{0},{1},{2},{3}", box1.Text, ddl1.SelectedItem.Text, box2.Text, box3.Text));
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
As you can see in the 1st column there is a button along with a textbox.
When you click the button, a popup window appears in which there is something like "search-in-the-database" mechanism.
So, when a value is selected in the popup window's gridview, I want to transfer it to the corresponding text box.
How do I transfer the value into the corresponding textbox? As a beginner, I am dealing a great difficulty into that part. Any help will be appreciated
I have a ckeck box field in grid view header.On checking this Check box all the check boxes
in grid view gets checked. Now i want to delete all the rows on button click.
Code for the check box in my aspx page is as follows:
<HeaderTemplate>
Select All: <asp:CheckBox ID="chkboxSelectAll" AutoPostBack="true" OnCheckedChanged="chkboxSelectAll_CheckedChanged"
runat="server"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkEmp" runat="server"></asp:CheckBox>
</ItemTemplate></asp:TemplateField>
In my code behind i have tried this but its not working:
also In my Grid view DataKeyNames="id" and bindgrid() method is working fine.
For selecting all rows:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grd.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grd.Rows)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
}
}
For deleting all selected rows
protected void btn_click(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grd.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grd.Rows)
{
// Only look in data rows, ignore header and footer rows
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
var id = Grd.DataKeys[row.RowIndex].Value;
SqlConnection con = new SqlConnection(constr);
string qry = "delete from empdetail where id=#id";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindgrid();
}
}
}
}
Please Help me. Error i got is "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
Your first problem is that you are searching for the chkEmp check box, but it does not exist in the header row, because foreach (GridViewRow row in Grd.Rows) will loop through all rows in the grid (including header, data and footer rows).
The ItemTemplate in your grid view markup applies to rows of type DataRow, so you need to restrict your searching for chkEmp to just data rows, like this:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grd.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grd.Rows)
{
// Only look in data rows, ignore header and footer rows
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkEmp");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
var id = Grd.DataKeys[row.RowIndex].Value;
SqlConnection con = new SqlConnection(constr);
string qry = "delete from empdetail where id=#id";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#id", id);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
bindgrid();
}
else
{
ChkBoxRows.Checked = false;
}
}
}
}
<asp:GridView ID="GrdAtt" runat="server" CssClass="table table-small-font table-bordered table-striped" Font-Size="Small" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="10" HeaderStyle-Font-Names="Arial" HeaderStyle-Font-Italic="true"
AutoGenerateColumns="False" EmptyDataText="No Data Found" OnRowDataBound="GrdEmplistFromAtt_RowDataBound"
HeaderStyle-ForeColor="#990000">
<Columns>
<asp:TemplateField HeaderText=" " HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
ItemStyle-Width="25px">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSingle" runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="10px"></ItemStyle>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top"
Font-Bold="true" />
<RowStyle Font-Size="Small" Height="1" Font-Italic="true" />
</asp:GridView>
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk_All = (CheckBox)GrdAtt.HeaderRow.FindControl("chkAll");
if (chk_All.Checked == true)
{
foreach (GridViewRow gvr in GrdEmplistFromAtt.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
if (chk_Single.Visible == true)
{
chk_Single.Checked = true;
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
}
else
{
foreach (GridViewRow gvr in GrdEmplistFromAtt.Rows)
{
CheckBox chk_Single = (CheckBox)gvr.FindControl("chkSingle");
chk_Single.Checked = false;
lblSelectedRecord.InnerText = "0";
}
}
}
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.