Dynamically add rows to GridView which contain web controls in ASP.NET - c#

Hi I'm having a great issue because I don't know where to start. I need to create a Gridview which has to buttons below it, a "Create Row" button and a "Delete Row" button. I want that everytime the "Create Row" button is pressed a new row to be added to the GridView, however the main problem is that I need that new row to be filled with different controls such as DropDownLists and TextBox, but I have no idea of how to do it properly. Here is an image of how I want the GridView to be:
Each row has 2 dropdown lists, two textbox and a button
I know that I need to bind the GridView to a data source such as a dataTable, but I have no idea if that will work with controls such as TextBox or DropDownLists. Sorry if I don't add any code because I really don't know where to start. Thank you.

If i understood it right u can follow this:
Create Gridview
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand" DataKeyNames="RowNumber">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" Visible="false" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect"
ToolTip="Select To Delete This Row" />
<asp:Label runat="server" ID="lblId" Text='<%# Bind("Id") %>'
Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Entry">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstEntry" Visible="false" Text='<%# Eval("FirstEntry") %>'></asp:Label>
<asp:DropDownList ID="ddlFirstEntry" runat="server" ClientIDMode="Static" CssClass="ddlFirstEntry">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Entry">
<ItemTemplate>
<asp:Label runat="server" ID="lblSecondEntry" Visible="false" Text='<%# Eval("SecondEntry") %>'></asp:Label>
<asp:DropDownList ID="ddlSecondEntry" runat="server" ClientIDMode="Static" CssClass="ddlSecondEntry">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Text Box">
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstTextBox" Visible="false"></asp:Label>
<asp:TextBox ID="txtFirstTextBox" runat="server" Text='<%# Eval("FirstTextBox") %>'
CssClass="txtFirstTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Text Box">
<ItemTemplate>
<asp:Label runat="server" ID="lblSecondTextBox" Visible="false"></asp:Label>
<asp:TextBox ID="txtFSecondTextBox" runat="server" Text='<%# Eval("SecondTextBox") %>'
CssClass="txtSecondTextBox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Second Text Box">
<ItemTemplate>
<asp:Button ID="btnSubmit" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in Code behind in Page_Load call this method
private void InitializeGrid()
{
try
{
ViewState["applicationDetail"] = null;
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("Id", typeof(int)),
new DataColumn("FirstEntry", typeof(string)),
new DataColumn("SecondEntry",typeof(string)),
new DataColumn("FirstTextBox", typeof(string)),
new DataColumn("SecondTextBox", typeof(string))
});
DataRow drRow = dt.NewRow();
drRow["Id"] = 1;
drRow["FirstEntry"] = string.Empty;
drRow["SecondEntry"] = string.Empty;
drRow["FirstTextBox"] = string.Empty;
drRow["SecondTextBox"] = string.Empty;
dt.Rows.Add(drRow);
ViewState["applicationDetail"] = dt;
GridView1.DataSource = ViewState["applicationDetail"];
}
catch (Exception ex)
{
throw;
}
}
InitializeGrid();
GridView1.DataBind();
On GridView1_RowDataBound Bind All your drop down controls
upto this will create a grid with one empty row.
Now On Add Button Click do following
protected void btnNewRow_Click(object sender, EventArgs e)
{
try
{
AddNewRowToGrid();
}
catch (Exception ex)
{
throw ex;
}
}
private void AddNewRowToGrid()
{
try
{
int rowIndex = 0;
if (ViewState["applicationDetail"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values _lblGuestId
DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList;
DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList;
TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox;
TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox;
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["FirstEntry"] = ddl1.SelectedValue;
dtCurrentTable.Rows[i - 1]["SecondEntry"] = ddl2.SelectedValue;
dtCurrentTable.Rows[i - 1]["FirstTextBox"] = txt1.Text;
dtCurrentTable.Rows[i - 1]["SecondTextBox"] = txt2.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["applicationDetail"] = dtCurrentTable;
GridView1.DataSource = dtCurrentTable;
GridView1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
catch (Exception ex)
{
throw ex;
}
}
private void SetPreviousData()
{
try
{
int rowIndex = 0;
if (ViewState["applicationDetail"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["applicationDetail"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
{
DropDownList ddl1 = GridView1.Rows[rowIndex].FindControl("ddlFirstEntry") as DropDownList;
DropDownList ddl2 = GridView1.Rows[rowIndex].FindControl("ddlSecondEntry") as DropDownList;
TextBox txt1 = GridView1.Rows[rowIndex].FindControl("txtFirstTextBox") as TextBox;
TextBox txt2 = GridView1.Rows[rowIndex].FindControl("txtSecondTextBox") as TextBox;
ddl1.SelectedValue = dtCurrentTable.Rows[i]["FirstEntry"].ToString();
ddl2.SelectedValue = dtCurrentTable.Rows[i]["SecondEntry"].ToString();
txt1.Text = dtCurrentTable.Rows[i]["FirstTextBox"].ToString();
txt2.Text = dtCurrentTable.Rows[i]["SecondTextBox"].ToString();
rowIndex++;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
For Deleting
On GridView1_RowCommand when check box is checked get row indexes of all the checked check box rows and keep it in some session or application variable.
On delete button click use that variable for deleting the rows.
I hope your problem will be solved.
As per your comment i am adding GridView1_RowDataBound for drop down bindings
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
DropDownList ddl1 = (e.Row.FindControl("ddlFirstEntry") as DropDownList);
Label lbl1 = (e.Row.FindControl("lblFirstEntry") as Label);
DropDownList ddl2 = (e.Row.FindControl("ddlSecondEntry") as DropDownList);
Label lbl2 = (e.Row.FindControl("lblSecondEntry") as Label);
ddl1.Items.Clear();
ddl1.AppendDataBoundItems = true;
ddl1.Items.Add(new ListItem("-Select-", "-1"));
ddl1.DataSource = ViewState["ddl1datasourse"];
ddl1.DataTextField = "Value";
ddl1.DataValueField = "Id";
ddl1.DataBind();
if (ddl1.SelectedValue != string.Empty && lbl1.Text != null)
ddl1.SelectedValue = lbl1.Text.Trim();
else
ddl1.SelectedValue = "-1";
ddl2.Items.Clear();
ddl2.AppendDataBoundItems = true;
ddl2.Items.Add(new ListItem("-Select-", "-1"));
ddl2.DataSource = ViewState["ddl2datasourse"];
ddl2.DataTextField = "Value";
ddl2.DataValueField = "Id";
ddl2.DataBind();
if (ddl2.SelectedValue != string.Empty && lbl2.Text != null)
ddl2.SelectedValue = lbl2.Text.Trim();
else
ddl2.SelectedValue = "-1";
}
catch (Exception ex)
{
throw ex;
}
}

Related

How to achieve bulk save in Gridview using ASP.NET with C#

I have got a Gridview which gets populated with multiple rows as follows where user is allowed to edit Alternate names for the viewed rows after he can bulk save the edited columns.
I tried achieving this using Edit template but I could not achieve this because when the user tries to edit the next row immediately the previous "edited" column contents are erased back to original.
How can I achieve this using gridview
On edit action of the GridView, your change happens only on your browser (client side) until you save the change of current row. You need to save the row and refresh GridView to begin editing the next row.
The typical implementation is to place two button on Edit template - Cancel and Save button to commit the change of the edited row. When clicking on the save button, your postback event will be picked up on server side code (with event argument e that contain which row was on edit and row data that you updated). You save the data to database and refresh the GridView. At that moment, you should be able to see the GridView with updated content. You are ready to click on the Edit button of the next row.
Use this and Edit According to you this is working for me perfectly.
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("[id$=txtRecievedDate]").datepicker({
showOn: 'button',
buttonImageOnly: true,
dateFormat: "yy-mm-dd",
buttonImage: 'http://jqueryui.com/demos/datepicker/images/calendar.gif'
});
});
</script>
<style type = "text/css">
input[type=text], select{background-color:#FFFFD2; border:1px solid #ccc}
</style>
</head>
<body style = "font-family:Arial;font-size:10pt">
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
DataKeyNames = "id" onrowdatabound="gvCustomers_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="SelectEdit"></asp:Label>
<asp:CheckBox ID = "chkAll" runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" OnCheckedChanged="OnCheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("id") %>'></asp:Label>
<asp:TextBox ID="txtID" runat="server" Text='<%# Eval("id") %>' ReadOnly="true" Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cartridge Set No" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>'></asp:Label>
<asp:TextBox ID="txtCartridgeSetNo" runat="server" Text='<%# Eval("CartridgeSetNo") %>' ReadOnly="true" Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID = "lblcurrentstatus" runat="server" Text='<%# Eval("currentstatus") %>'></asp:Label>
<asp:Label ID = "lblstatus" runat="server" Text='<%# Eval("status") %>' Visible = "false"></asp:Label>
<asp:DropDownList ID="ddlstatus" runat="server" Visible = "false">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="date Recieved" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("dateRecieved") %>'></asp:Label>
<asp:TextBox ID="txtRecievedDate" runat="server" Text='<%# Eval("dateRecieved") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments" ItemStyle-Width = "150">
<ItemTemplate>
<asp:Label ID="lblComments" runat="server" Text='<%# Eval("comments") %>'></asp:Label>
<asp:TextBox ID="txtComments" runat="server" Text='<%# Eval("comments") %>' Visible="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick = "Update" Visible = "false"/>
</form>
</body>
</html>
CS file
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
SqlCommand cmd = new SqlCommand("SELECT [Id],[CartridgeSetNo],[status] ,[dateRecieved],[Comments] ,case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as currentstatus FROM DrugAllocate ");
gvCustomers.DataSource = this.ExecuteQuery(cmd, "SELECT");
gvCustomers.DataBind();
}
private DataTable ExecuteQuery(SqlCommand cmd, string action)
{
string conString = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
switch (action)
{
case "SELECT":
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
case "UPDATE":
con.Open();
cmd.ExecuteNonQuery();
con.Close();
break;
}
return null;
}
}
protected void Update(object sender, EventArgs e)
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
SqlCommand cmd = new SqlCommand("UPDATE DrugReceipt SET Comments=#Comments, dateRecieved=#dateRecieved , status = #status where Id = #Id");
cmd.Parameters.AddWithValue("#Comments", row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text);
string status = row.Cells[3].Controls.OfType<DropDownList>().FirstOrDefault().SelectedItem.Value;
if (status == "Received and Usable")
{
status="0";
}
if (status == "Received but not usable")
{
string comments=row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text;
status = "1";
if (comments == "")
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('comment is mendatry');", true);
break;
}
}
if (status == "Not Received")
{
status = "2";
}
cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters.AddWithValue("#dateRecieved", row.Cells[4].Controls.OfType<TextBox>().FirstOrDefault().Text);
cmd.Parameters.AddWithValue("#Id", gvCustomers.DataKeys[row.RowIndex].Value);
this.ExecuteQuery(cmd, "UPDATE");
}
}
}
btnUpdate.Visible = false;
this.BindGrid();
}
public DataSet GetYesNoValue(string ColumnName)
{
DataTable dtVal = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = ColumnName;
dtVal.Columns.Add(column);
DataSet dsVal = new DataSet();
dtVal.Rows.Add("Received and Usable");
dtVal.Rows.Add("Received but not usable");
dtVal.Rows.Add("Not Received");
dsVal.Tables.Add(dtVal);
return dsVal;
}
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool isUpdateVisible = false;
CheckBox chk = (sender as CheckBox);
if (chk.ID == "chkAll")
{
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked = chk.Checked;
}
}
}
CheckBox chkAll = (gvCustomers.HeaderRow.FindControl("chkAll") as CheckBox);
chkAll.Checked = true;
foreach (GridViewRow row in gvCustomers.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
for (int i = 1; i < row.Cells.Count; i++)
{
row.Cells[i].Controls.OfType<Label>().FirstOrDefault().Visible = !isChecked;
if (row.Cells[i].Controls.OfType<TextBox>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<TextBox>().FirstOrDefault().Visible = isChecked;
}
if (row.Cells[i].Controls.OfType<DropDownList>().ToList().Count > 0)
{
row.Cells[i].Controls.OfType<DropDownList>().FirstOrDefault().Visible = isChecked;
}
if (isChecked && !isUpdateVisible)
{
isUpdateVisible = true;
}
if (!isChecked )
{
chkAll.Checked = false;
}
}
}
}
btnUpdate.Visible = isUpdateVisible;
}
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd = new SqlCommand("SELECT status, case when status = 1 then 'Received but not usable' when status = 0 then 'Received and Usable' else 'Not Received' end as statuscurrent FROM DrugAllocate");
DropDownList ddlstatus = (e.Row.FindControl("ddlstatus") as DropDownList);
ddlstatus.DataSource = this.ExecuteQuery(cmd, "SELECT");
string country = (e.Row.FindControl("lblstatus") as Label).Text;
DataSet ds = new DataSet();
ds = GetYesNoValue("suppStatus");
DataTable dt = new DataTable();
dt = ds.Tables[0];
ddlstatus.DataSource = dt;
ddlstatus.DataTextField = "suppStatus";
ddlstatus.DataValueField = "suppStatus";
ddlstatus.DataBind();
try
{
ddlstatus.Items.FindByValue(country).Selected = true;
}
catch { }
}
}
}

Need to click the button twice to edit and update gridview data

In my application i need to edit the gridview rows on clicking the edit button of that particular row everything works fine edit update and cancel the problem is when i click edit button my gridview disappears again to see the gridview i should click the below button
<asp:Button ID="Button1" runat="server" style="border:1px solid #456879;border-radius:5px;height: 22px;Width:150px" OnClick="Button1_Click" Text="Get Uploaded Data" Width="132px" />
and similarly after updating my gridview disappears but update happens so to again see the gridview i should again click the above button Get Uploaded Data,Finally in order to edit gridview data i need to click the button twice and in order to see the updated data again i need to click the button twice.How can i solve this
<asp:GridView ID="GridView2" runat="server" CellPadding="3" Font-Size="12px" Width="300px" Visible="false" OnRowEditing="GridView2_RowEditing" OnRowUpdating="GridView2_RowUpdating" OnRowCommand="GridView2_RowCommand" OnRowCancelingEdit="GridView2_RowCancelingEdit" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px">
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="Images/icon-edit.png" Height="32px" Width="32px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="Images/update1.jpg"/>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="Images/cancel.jpg"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:templatefield headertext="sno">
<itemtemplate>
<asp:label id="lblid" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "ID") %>'></asp:label>
</itemtemplate>
<edititemtemplate>
<asp:label id="lbleditid" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "ID") %>'></asp:label>
</edititemtemplate>
</asp:templatefield>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditName" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<ItemTemplate>
<asp:Label ID="lblSalary" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Salary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditSalary" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Salary") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Designation") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Designation") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Location") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditLocation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Location") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.Cs Code
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView2.EditIndex = e.NewEditIndex;
GridView2.DataBind();
GridView2.Visible = true;
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblEditID = (Label)GridView2.Rows[e.RowIndex].FindControl("lblEditID");
TextBox txtEditName = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditName");
TextBox txtEditSalary = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditSalary");
TextBox txtEditDesignation = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditDesignation");
TextBox txtEditLocation = (TextBox)GridView2.Rows[e.RowIndex].FindControl("txtEditLocation");
con.Open();
string cmdstr = "update CodingLog1 set Name=#Name,Salary=#Salary,Designation=#Designation,Location=#Location where ID=#ID";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#ID", lblEditID.Text);
cmd.Parameters.AddWithValue("#Name", txtEditName.Text);
cmd.Parameters.AddWithValue("#Salary", txtEditSalary.Text);
cmd.Parameters.AddWithValue("#Designation", txtEditDesignation.Text);
cmd.Parameters.AddWithValue("#Location", txtEditLocation.Text);
cmd.ExecuteNonQuery();
con.Close();
GridView2.EditIndex = -1;
GridView2.Visible = true;
GridView2.DataBind();
}
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView2.EditIndex = -1;
GridView2.Visible = true;
GridView2.DataBind();
}
Button code-
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = null; GridView1.DataBind();
string desi = Session["Role"].ToString();
string user = Session["Username"].ToString();
string selecteduser = ddlusers.SelectedItem.Text;
if (TextBox1.Text != "")
{
if (rdupldeddate.Checked == true)
{
DataTable dt = adm.GetRecordsByUploadedDate(user, TextBox1.Text, desi, selecteduser); //Uploaded date
if (dt.Rows.Count > 0)
{
if (desi == "Supervisor")
{
BtnExport.Visible = true;
GridView2.Visible = true;
GridView1.Visible = false;
GridView2.DataSource = dt;
GridView2.DataBind();
}
else
{
GridView2.Visible = false;
BtnExport.Visible = false;
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else { lblMsg.Visible = true; GridView1.Visible = false; GridView2.Visible = false; lblMsg.Text = "No Data Present!!!"; }
}
else
{
DataTable dt = adm.GetRecordsByCodedDate(user, TextBox1.Text, desi, selecteduser); //CodedDate
if (dt.Rows.Count > 0)
{
if (desi == "Supervisor")
{
BtnExport.Visible = true;
GridView2.Visible = true;
GridView1.Visible = false;
GridView2.DataSource = dt;
GridView2.DataBind();
}
else
{
GridView2.Visible = false;
BtnExport.Visible = false;
GridView1.Visible = true;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else { lblMsg.Visible = true; GridView1.Visible = false; GridView2.Visible = false; lblMsg.Text = "No Data Present!!!"; }
}
}
else { lblMsg.Visible = true; lblMsg.Text = "Please Enter Date!!!"; }
}
I had tried all the possibilties by taking editindex=0 instead of -1, by calling my gridview2.databind in !ispostback moreover i had placed my gridview in update panel also but still its not working
In your GridView2_RowUpdating, you are updating your data on the database and binding your GridView2 to nothing. That's why the GridView disappears. It has no data to show. While the button you click fetch the updated data and binds it to the GridView that's why it shows again. When you update the data, you should fetch the updated data and rebind it to your GridView again.
I suggest using DataSet and assign as Datasource before calling GridView2.DataBind();
SqlDataAdapter da = new SqlDataAdapter(cmdstr ,con);
da.SelectCommand.CommandType = CommandType.Text;
da.SelectCommand.Parameters.AddWithValue("#ID", lblEditID.Text);
da.SelectCommand.Parameters.AddWithValue("#Name", txtEditName.Text);
da.SelectCommand.Parameters.AddWithValue("#Salary", txtEditSalary.Text);
da.SelectCommand.Parameters.AddWithValue("#Designation", txtEditDesignation.Text);
da.SelectCommand.Parameters.AddWithValue("#Location", txtEditLocation.Text);
DataSet dsResult = new DataSet();
da.Fill(dsResult);
con.Close();
GridView2.DataSource = dsResult;
GridView.DataBind();
Or Call the codes in your button through a method after the update.
Try this if this works.
Based on the code you pasted into the comments, the problem lies in your Page_Load event handler. The code that sets the initial visibility of the GridViews should be inside the if (!IsPostBack) block.
lblMsg.Text = "";
if (!IsPostBack)
{
BindUsers();
// Set the initial visibility of grids here
string desi = Session["Role"].ToString();
if (desi == "Supervisor")
{
GridView2.Visible = true;
GridView1.Visible = false;
ddlusers.Visible = true;
BtnExport.Visible = false;
}
else
{
GridView2.Visible = false;
GridView1.Visible = true;
ddlusers.Visible = false;
BtnExport.Visible = false;
}
}
Once you have set the visibility for those grids on the first page load, that setting will be maintained by the ViewState across postbacks. From that point on, it appears that your control events are managing the visibility of the grids (based on whether there are results to show, etc).

How to checked my checkbox according to the data from database

<asp:TemplateField HeaderText="CAT A or CAT C">
<ItemTemplate>
<asp:CheckBox ID="chkcata" OnCheckedChanged="chkcata_CheckedChanged" OnDataBinding="chkcata_DataBinding" runat="server" Text='<%# Eval("cat_a") %>' Checked='<%# Eval("cat_a").ToString().Equals("1")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Port to Trikon">
<ItemTemplate>
<asp:CheckBox ID="chkport" Style="text-align: center" OnCheckedChanged="chkport_CheckedChanged" OnDataBinding="chkport_DataBinding" runat="server" Text='<%# Eval("Port_Trikon") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="White Pages Listing? Y/N">
<ItemTemplate>
<asp:CheckBox ID="chkwhilepages" Style="text-align: center" OnCheckedChanged="chkwhilepages_CheckedChanged" OnDataBinding="chkwhilepages_DataBinding" runat="server" Text='<%# Eval("while_pages") %>' />
</ItemTemplate>
</asp:TemplateField>
the image u can see which is my gridview, in which the checkbox are given. Now on update time when i execute my filladd() function the checkbox are not checked even they are true so please help it out..!!
private void filladd(int p)
{
DataTable dt = new DataTable();
dt = b.get_subpaf(p);//MJ SP CHANGE
if (dt.Rows.Count > 0)
{
DataExtensionList.DataSource = dt;
DataExtensionList.DataBind();
ViewState["ExtensionId"] = dt.Rows.Count;
ExtensionBind();
}
}
<asp:CheckBox ID="chkport" runat="server" Checked='<%# DataBinder.Eval (Container.DataItem,"Port_Trikon").ToString()!="0"?true:false %>' />
Make sure that Database is either BIT datatype or just return 1, 0 string
i got the above answer just replace this function with the old one which is asked in question
private void filladd(int p)
{
DataTable dt = new DataTable();
dt = b.get_subpaf(p);//MJ SP CHANGE
if (dt.Rows.Count > 0)
{
DataExtensionList.DataSource = dt;
DataExtensionList.DataBind();
foreach (GridViewRow it1 in DataExtensionList.Rows)
{
CheckBox chk = (CheckBox)it1.FindControl("chkcata");
CheckBox chk1 = (CheckBox)it1.FindControl("chkport");
CheckBox chk2 = (CheckBox)it1.FindControl("chkwhilepages");
if (chk.Text == "True")
{
chk.Checked = true;
}
if (chk1.Text == "True")
{
chk1.Checked = true;
}
if (chk2.Text == "True")
{
chk2.Checked = true;
}
}
}
}

default multiple rows in a gridview using asp.net c#?

i want multiple rows default in a gridview..
but i have a code like,
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
after click "Add New Row" button in .cs file ,
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
http://www.aspsnippets.com/Articles/Adding-Dynamic-Rows-in-ASP.Net-GridView-Control-with-TextBoxes.aspx
here only 1 row is there default, but i need atleast 4 rows,
then how to save that in db too.
help...

Getting exception while deleting rows from GridView

I want to delete selected rows from a GridView. For this I have written the below code, but I am getting an exception:
An unhandled exception of type 'System.StackOverflowException' occurred in System.Web.dll
Here is my aspx.page:
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
onrowcommand="Gridview1_RowCommand" AutoGenerateColumns="false"
CellSpacing="0" CellPadding="0" Font-Bold="false"
onrowdeleting="Gridview1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Select" ControlStyle-Width="50px" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Width="80px"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 1" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Total" Font-Bold="true"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="TextBox2" Width="70px" runat="server" class="calculate" onchange="calculate()"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="total" runat="server" Width="70px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3" HeaderStyle-Font-Bold="false" ControlStyle-Font-Bold="false">
<ItemTemplate>
<asp:TextBox ID="TextBox3" Width="70px" runat="server" ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" CommandName="AddNewRow" />
<asp:Button ID="btnDelete" runat="server" CommandName="DeleteRow" Text="Delete"
OnClientClick="return DeleteConfirmation();"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Here is the code behind the aspx page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
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)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
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 = 1; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddNewRow")
{
AddNewRowToGrid();
}
if (e.CommandName == "DeleteRow")
{
for (int i = 0; i < Gridview1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
Gridview1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
//strID = GridView1.Rows[i].Cells[1].Text;
//idCollection.Add(strID);
Gridview1.DeleteRow(i);
}
}
}
}
Gridview1.DataBind();
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
for (int i = 0; i < Gridview1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox)
Gridview1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
//strID = GridView1.Rows[i].Cells[1].Text;
//idCollection.Add(strID);
Gridview1.DeleteRow(i);
}
}
}
Gridview1.DataBind();
}
}
I don't think you need to implement the RowDeleting event in your code. The RowDeleting event is just there to inform the program that a row is gonna get deleted.
In your example the RowDeleting event is calling the DeleteRow method, wich will cause RowDeleting event to be triggered and then the circle will just happend again. This circle will eventually end when the computer sees no other option then to cause a StackOverflowException and end your program.

Categories

Resources