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).
Related
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 { }
}
}
}
<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;
}
}
}
}
I have a Gridview "Gridview_ActionPlan" with DataKey "ID" and a RowDataBound event that colors certain cells according to the value of the datasource. Until here everything fine. Now I added a command to give visibility to one column based on a condition and it throws the error "Column 'ID' does not belong to table DefaultView"
if (e.Row.Cells[3].Text != "1" && e.Row.Cells[2].Text != "2")
{
Gridview_ActionPlan.Columns[5].Visible = true;
LinkButton LB2 = e.Row.Cells[5].FindControl("ButtonOpen") as LinkButton;
LB2.Visible = true;
}
... and Columns[5]
<asp:templatefield ItemStyle-HorizontalAlign="center" Visible="false">
<ItemTemplate>
<asp:LinkButton ID="ButtonOpen" runat="server" CommandArgument = '<%# Eval("ID") %>' OnClick="OpenNode" style="vertical-align:text-bottom;text-decoration:none" Visible="false">
<asp:Image runat="server" src="img/plus_.png" id="OpenNodeIMG" border="0" Visible="true"/>
</asp:LinkButton>
</ItemTemplate>
</asp:templatefield>
Now if I give static visibility to that column and remove "Gridview_ActionPlan.Columns[5].Visible = true;" then no error is thrown. This doesn't make sense to me
Martin
Here is the full OnRowDataBound event:
Comment: The SQLConnection part fills the grid with the correct headers according to the chosen language. This is kind of time consuming so if someone has a better idea, feel free... although this is not the issue of that post
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
var gv = (GridView)sender;
string GridID = Convert.ToString(gv.ID);
SqlConnection objConn = new SqlConnection("Data Source=XXXXXX");
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand objCommand = new SqlCommand(#"select Text
from EPC_Menu
where language = #language and MenuControlID = #GridID
order by MenuID", objConn);
objCommand.Parameters.Add("#GridID", SqlDbType.NVarChar).Value = GridID;
objCommand.Parameters.Add("#language", SqlDbType.NVarChar).Value = LanguageLabel.Text;
DataSet t = new DataSet();
adapter.SelectCommand = objCommand;
objConn.Open();
adapter.Fill(t);
objConn.Close();
if (e.Row.RowType == DataControlRowType.Header)
{
for(int i = 0; i+6 < gv.Columns.Count; i++)
{
if (t.Tables[0].Rows.Count > 0)
{
e.Row.Cells[i+6].Text = t.Tables[0].Rows[i][0].ToString();
}
}
}
else
{
if (e.Row.Cells[1].Text == "True")
{
e.Row.Cells[9].BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFF00");
e.Row.Cells[10].BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFF00");
}
else if (e.Row.Cells[2].Text == "2")
{
e.Row.BackColor = System.Drawing.ColorTranslator.FromHtml("#CCECF4");
}
if (e.Row.Cells[3].Text != "1" && e.Row.Cells[2].Text != "2" && !string.IsNullOrEmpty(e.Row.Cells[3].Text) && e.Row.RowType == DataControlRowType.DataRow && Gridview_ActionPlan.EditIndex != e.Row.RowIndex)
{
LinkButton LB2 = e.Row.Cells[5].FindControl("ButtonOpen") as LinkButton;
LB2.Visible = true;
}
}
}
here goes the gridview with columns 0 - 5 is already posted:
<asp:GridView ID="Gridview_ActionPlan" runat="server"
DataSourceID="ActionPlan"
DataKeyNames="ID"
AutoGenerateColumns="false"
Font-Names="Arial"
OnRowDataBound="OnRowDataBound">
<RowStyle BorderColor="White"
Font-Size="12px" VerticalAlign="Bottom" />
<Columns>
<asp:BoundField DataField="ID"
ItemStyle-CssClass="hiddencol"
HeaderStyle-CssClass="hiddencol" />
<asp:BoundField DataField="CustomerRequired"
ItemStyle-CssClass="hiddencol"
HeaderStyle-CssClass="hiddencol" />
<asp:BoundField DataField="Type"
ItemStyle-CssClass="hiddencol"
HeaderStyle-CssClass="hiddencol" />
<asp:BoundField DataField="CNT"
ItemStyle-CssClass="hiddencol"
HeaderStyle-CssClass="hiddencol" />
<asp:TemplateField ItemStyle-HorizontalAlign="left"
ItemStyle-Width="50px" Visible="false">
<ItemTemplate>
<asp:ImageButton ID="LINKButton2" runat="server"
CommandName="Edit"
ImageUrl="img/edit.png"
Style="vertical-align: text-bottom" />
<asp:LinkButton ID="ButtonSelect" runat="server"
CommandName="Select"
CommandArgument='<%# Eval("ID") %>'
Style="vertical-align: text-bottom; text-decoration: none"
OnClick="AddNewMileStone" Visible="true">
<asp:Image runat="server" ID="ImageMS"
ImageUrl="img/select.png"
Style="vertical-align: text-bottom; text-decoration: none"
BorderStyle="None" />
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="InsertButton" runat="server"
CommandName="Update"
ImageUrl="img/save.png"
Style="vertical-align: text-bottom" />
<asp:ImageButton ID="LINKButton2" runat="server"
CommandName="Cancel"
ImageUrl="img/cancel2.jpg"
Style="vertical-align: text-bottom" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="center"
Visible="false">
<ItemTemplate>
<asp:LinkButton ID="ButtonOpen" runat="server"
CommandArgument = '<%# Eval("ID") %>'
OnClick="OpenNode"
style="vertical-align:text-bottom;text-decoration:none"
Visible="false">
<asp:Image id="OpenNodeIMG" runat="server"
src="img/plus_.png"
border="0"
Visible="true"/>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is kind of time consuming so if someone has a better idea, feel free... although this is not the issue of that post
Actually this should be a major issue. You are doing three things wrong here.
You are calling the function to fill the dataset in each iteration of RowDataBound. If you have 20 rows and 1 header that will be 20 unnecessary call to database
No need to open() the connection to fill a dataset using a data-adapter
No need to qualify .FindControl with Cells[cell_index]`.
So move your code after your Gridviews DataBind() event. Pseudo code will be,
Gridview_ActionPlan.DataBind();
DataSet t = new DataSet();
var gv = Gridview_ActionPlan;
string GridID = Convert.ToString(gv.ID);
using (SqlConnection objConn = new SqlConnection("Data Source=XXXXXX"))
using (SqlCommand objCommand = new SqlCommand(#"select Text
from EPC_Menu
where language = #language and MenuControlID = #GridID
order by MenuID", objConn))
{
SqlDataAdapter adapter = new SqlDataAdapter();
objCommand.Parameters.Add("#GridID", SqlDbType.NVarChar).Value = GridID;
objCommand.Parameters.Add("#language", SqlDbType.NVarChar).Value = LanguageLabel.Text;
adapter.SelectCommand = objCommand;
adapter.Fill(t);
}
var headerRow = gv.HeaderRow;
for (int i = 0; i + 6 < gv.Columns.Count; i++)
{
if (t.Tables[0].Rows.Count > 0)
{
headerRow.Cells[i + 6].Text = t.Tables[0].Rows[i][0].ToString();
}
}
for (int i = 0; i < gv.Rows.Count; i++)
{
if (gv.Rows[i].Cells[1].Text == "True")
{
gv.Rows[i].Cells[9].BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFF00");
gv.Rows[i].Cells[10].BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFF00");
}
else if (gv.Rows[i].Cells[2].Text == "2")
{
gv.Rows[i].BackColor = System.Drawing.ColorTranslator.FromHtml("#CCECF4");
}
if (gv.Rows[i].Cells[3].Text != "1" &&
gv.Rows[i].Cells[2].Text != "2" &&
!string.IsNullOrEmpty(gv.Rows[i].Cells[3].Text) &&
gv.Rows[i].RowType == DataControlRowType.DataRow &&
Gridview_ActionPlan.EditIndex != gv.Rows[i].RowIndex)
{
LinkButton LB2 = gv.Rows[i].FindControl("ButtonOpen") as LinkButton;
LB2.Visible = true;
}
}
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;
}
}
I am sorting my date with my sql query and I get a proper result.
But as I apply
gridview.UseAccessibleHeader = true;
gridview.HeaderRow.TableSection = TableRowSection.TableHeader;
to my gridview. The sorted data gets unsorted.
this.gridviewname.MasterTemplate.EnableSorting = true;
this.RadGridView1.MasterTemplate.EnableSorting = True
SortDescriptor descriptor = new SortDescriptor();
descriptor.PropertyName = "Yourcolumnname";
descriptor.Direction = ListSortDirection.Ascending;
this.gridviewname.MasterTemplate.SortDescriptors.Add(descriptor);
descriptorcolumnname As New SortDescriptor()
descriptorShipName.PropertyName = "columnname"
descriptorShipName.Direction = ListSortDirection.Ascending
try this
Try this code which is working fine for me.
-- C# Code here---
<form id="form1" runat="server">
<div>
<h1>Gridview Property of Sorting</h1>
<br />
<asp:GridView ID="gdviewevent" runat="server" AutoGenerateColumns="false" OnSorting="gdviewevent_Sorting" AllowSorting="true">
<HeaderStyle BackColor="YellowGreen" Font-Bold="True" Font-Names="cambria" ForeColor="Black" />
<RowStyle Font-Names="Calibri" />
<Columns>
<asp:TemplateField HeaderText="Sr No.">
<ItemTemplate>
<span><%#Container.DataItemIndex+1 %></span>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="India Value" SortExpression="IndiaVal">
<ItemTemplate>
<asp:Label ID="lblindiavalue" runat="server" Text='<%#Eval("Column1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date" SortExpression="Registereddate">
<ItemTemplate>
<asp:Label id="lblcreateddate" runat="server" Text='<%#Eval("Registereddate", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
-- Page behind Code ---
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGridView();
}
}
protected void FillGridView()
{
string query = "Select Column1, Registereddate from tablename";
SqlCommand cmd = new SqlCommand(query, con);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.Rows.Count > 0)
{
gdviewevent.DataSource = dt;
gdviewevent.DataBind();
ViewState["dirState"] = dt;
ViewState["sortdr"] = "Asc";
}
}
protected void gdviewevent_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtrslt = (DataTable)ViewState["dirState"];
if (dtrslt.Rows.Count > 0)
{
if (Convert.ToString(ViewState["sortdr"]) == "Asc")
{
dtrslt.DefaultView.Sort = e.SortExpression + " Desc";
ViewState["sortdr"] = "Desc";
}
else
{
dtrslt.DefaultView.Sort = e.SortExpression + " Asc";
ViewState["sortdr"] = "Asc";
}
gdviewevent.DataSource = dtrslt;
gdviewevent.DataBind();
}
}