how to find datakeys in oncheckedchanged event? - c#

<asp:Panel ID="pnlFocusAreaPanel" runat="server" GroupingText="Focus Area" Width="800">
<table cellspacing="0" cellpadding="0" width="750">
<tr>
<td>
<asp:GridView ID="dgFocusAreaDetails" runat="server" Width="100%" CssClass="dgStyle"
AutoGenerateColumns="False" BorderColor="Silver" BorderWidth="1px" CellPadding="0"
ShowHeader="False" OnSelectedIndexChanged="dgFocusAreaDetails_SelectedIndexChanged"
DataKeyNames="PK_ID">
<FooterStyle Font-Underline="True" HorizontalAlign="Center" VerticalAlign="Middle">
</FooterStyle>
<Columns>
<asp:TemplateField HeaderText="Focus Area" HeaderStyle-BackColor="Silver">
<ItemStyle Width="90%" />
<ItemTemplate>
<asp:Label runat="server" ID="lblFocusArea" Text='<%# DataBinder.Eval(Container.DataItem, "FOCUS_AREA_NAME").ToString()%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Current Valid" HeaderStyle-BackColor="Silver">
<ItemStyle Width="10%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkFocusArea" runat="server" OnCheckedChanged="OnCheckChangedEvent"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td align="left">
<asp:TextBox ID="txtFocusArea" runat="server" Width="300px" CausesValidation="true" CssClass="txtStyle" ValidationGroup="focusArea">
</asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtFocusAreaWaterMark" runat="server" TargetControlID="txtFocusArea"
WatermarkText="Add Focus Area" WatermarkCssClass="WaterMarkStyle">
</cc1:TextBoxWatermarkExtender>
<asp:Button ID="btnAddFocusArea" runat="server" Text="AddFocusArea" CssClass="btnStyle"
OnClick="btnAddFocusArea_Click" CausesValidation="true" ValidationGroup="focusArea" />
<asp:RequiredFieldValidator ID="reqtxtFocusArea" runat="server" ControlToValidate="txtFocusArea"
ErrorMessage="Please enter focus area" Display="Dynamic" ValidationGroup="focusArea">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexFocusArea" runat="server" ErrorMessage="Invalid characters(<,>,#)"
ControlToValidate="txtFocusArea" ValidationExpression="^([^<#>]*)$" ValidationGroup="focusArea"
Display="Dynamic" SetFocusOnError="true">
</asp:RegularExpressionValidator>
</td>
</tr>
</table>
</asp:Panel>
and in code behind
protected void btnAddFocusArea_Click(object sender, EventArgs e)
{
string strFocusArea = txtFocusArea.Text;
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
if (strFocusArea == string.Empty || strFocusArea == txtFocusAreaWaterMark.WatermarkText)
{
lblError.Text = "Focus area is not entered";
}
else
{
string insertQuery = "INSERT INTO LK_CODECAT_FOCUS_AREA(FOCUS_AREA_NAME,FK_ADDED_BY,ADDED_ON) "+
" VALUES('" + strFocusArea + "', "+Session["UserID"] +", GETDATE())";
try
{
myConnection.Open();
OleDbCommand myCommandToInsert = new OleDbCommand(insertQuery, myConnection);
myCommandToInsert.ExecuteNonQuery();
}
catch(Exception exc)
{
ExceptionLogger.LogException(exc);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
PopulateFocusArea();
}
txtFocusArea.Text = txtFocusAreaWaterMark.WatermarkText;
}
private void PopulateFocusArea()
{
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
string selectQuery = "SELECT PK_ID, FOCUS_AREA_NAME, IS_CURRENT_FOCUS FROM LK_CODECAT_FOCUS_AREA LKCFA ORDER BY FOCUS_AREA_NAME";
if (Session["RoleID"].ToString() == "1" || ((Session["WorkID"].ToString() != "9") ||
(Session["WorkID2"].ToString() != "9") ||
(Session["WorkID3"].ToString() != "9")))
{
try
{
myConnection.Open();
OleDbCommand myCommandFocusArea = new OleDbCommand(selectQuery, myConnection);
OleDbDataAdapter myAdapter = new OleDbDataAdapter(myCommandFocusArea);
DataSet ds = new DataSet();
myAdapter.Fill(ds);
dgFocusAreaDetails.DataSource = ds;
dgFocusAreaDetails.ShowHeader = true;
dgFocusAreaDetails.DataBind();
}
catch (Exception exc)
{
ExceptionLogger.LogException(exc);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
}
}
protected void dgFocusAreaDetails_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCategory = dgFocusAreaDetails.SelectedRow.Cells[1].Text;
int index = dgFocusAreaDetails.SelectedIndex;
lblError.Text = dgFocusAreaDetails.DataKeys[index].Value.ToString();
}
public void OnCheckChangedEvent(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
string chkfocusarea = ((Control)chk).ID;
//string focusAreaDetails = dgFocusAreaDetails.SelectedRow.Cells[0].Text;
int index =Convert.ToInt32(dgFocusAreaDetails.SelectedIndex);
if (chk.Checked)
{
string updateQuery = "UPDATE [LK_CODECAT_FOCUS_AREA] SET [IS_CURRENT_FOCUS] = 1 WHERE PK_ID = "
+Convert.ToInt32( dgFocusAreaDetails.DataKeys[index].Value)+" ";
}
else
{
lblError.Text = "unchecked";
}
}
i want to know how i find the datakeyvalue on checked event because updateQuery in checked event is generating exception.

Could you add a asp:button instead of using the checkbox on your GridView and fire an OnRowUpdating event?
Alternatively you could store the index value in a session varaible to pick up on your chkbox click.
edit: found this post is that any help?
They suggest you have to check each row to see if the value has changed.

Related

C#- Maintain State of Checkbox and textbox in gridview on page changing

I have a gridview having a textbox and a checkbox.when the checkbox is checked,a value will be populated into the textbox which a user may alter the value.
Here is the code for the gridview
<asp:GridView ID="gvPayment" runat ="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="Vertical" Width="100%" ShowFooter="true" CssClass="jumbSize1" OnRowDataBound="gvPayment_RowDataBound" AllowPaging="true" PageSize="5" OnPageIndexChanging="gvPayment_PageIndexChanging" >
<Columns>
<asp:TemplateField HeaderStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" CssClass="checkbox" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TRANSACTION DATE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="SalesDate" runat="server" Text='<%#Eval("Date", "{0:dd/MM/yyyy}") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Submit" Text="Submit" runat="server" OnClick="Submit_Click" CssClass="btn btn-primary" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sales Code" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="SalesCode" runat="server" Text='<%#Eval("SALES_CODE") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label Text="Page Totals" runat="server" align="right" />
</div>
<div>
<asp:Label Text="Grand Totals" runat="server" align="right" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ACTUAL SALE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="ActualSales" runat="server" Text='<%#Eval("ACTUAL", "{0:N2}") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label ID="PageActual" runat="server" align="right" />
</div>
<div>
<asp:Label ID="GrandActual" runat="server" align="right" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ADVANCE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="AdvPay" runat="server" Text='<%#Eval("ADVANCE", "{0:N2}") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label ID="PageAdvance" runat="server" align="left" />
</div>
<div>
<asp:Label ID="GrandAdvance" runat="server" align="left" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AMOUNT DUE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="AmtDue" runat="server" Text='<%#Eval("DUE", "{0:N2}") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label ID="PageDue" runat="server" align="left" />
</div>
<div>
<asp:Label ID="GrandDue" runat="server" align="left" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AMOUNT PAID" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:TextBox ID="AmtPaid" runat="server" CssClass="form-control CapLock" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#4870BE" ForeColor="#FFFFFF" />
<FooterStyle BackColor="#76543c" ForeColor="#FFFFFF" Font-Bold="true" />
<HeaderStyle BackColor="#76543c" ForeColor="#FFFFFF" Font-Bold="true" />
<PagerSettings Mode="NextPrevious" NextPageText="Next &gt;&gt;" PreviousPageText="Prev &lt;&lt;" />
<PagerStyle BackColor="#76543c" ForeColor="#FFFFFF" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" /></asp:Gridview>
Here is the code to bind gridview to data source and get the grand totals in viewstate
private void GetCustomer()
{
dt = new DataTable();
try
{
using (con = new SqlConnection(conString))
{
using (cmd = con.CreateCommand())
{
string query = #"dbo.sp_get_sales";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ID", CustInfo.SelectedValue);
con.Open();
da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
//CALCULATE THE TOTAL AMOUNTS AND HOLD THE VALUE IN A "VIEWSTATE"
ViewState["TotalActual"] = null;
if (ViewState["TotalActual"] == null)
{
Decimal dActual = 0;
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dActual += dt.Rows[i].Field<Decimal>("ACTUAL");
}
ViewState["TotalActual"] = dActual.ToString("N2");
}
ViewState["TotalAdvance"] = null;
if (ViewState["TotalAdvance"] == null)
{
Decimal dAdvance = 0;
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dAdvance += dt.Rows[i].Field<Decimal>("ADVANCE");
}
ViewState["TotalAdvance"] = dAdvance.ToString("N2");
}
ViewState["TotalDue"] = null;
if (ViewState["TotalDue"] == null)
{
Decimal dDue = 0;
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dDue += dt.Rows[i].Field<Decimal>("DUE");
}
ViewState["TotalDue"] = dDue.ToString("N2");
}
}
//BIND QUERY RESULT WITH THE GRIDVIEW
gvPayment.DataSource = dt;
gvPayment.DataBind();
}
}
catch (Exception ex)
{
ErrorMessage.Text = "An error occured: " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
}
foreach (GridViewRow row in gvPayment.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
TextBox AmtPaid = (TextBox)row.FindControl("AmtPaid");
AmtPaid.Attributes.Add("readonly", "readonly");
}
}
}
Here is the code to enable and populate textbox on check changed event
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox chkSelect = (CheckBox)gvPayment.Rows[index].FindControl("chkSelect");
TextBox AmtPaid = (TextBox)gvPayment.Rows[index].FindControl("AmtPaid");
Label AmtDue = (Label)gvPayment.Rows[index].FindControl("AmtDue");
if (chkSelect.Checked && chkSelect != null)
{
AmtPaid.Text = AmtDue.Text.Replace(",", "");
AmtPaid.Attributes.Remove("readonly");
}
else
{
AmtPaid.Text = string.Empty;
AmtPaid.Attributes.Add("readonly", "readonly");
}
}
The textbox get populated with the desired value when the checkbox is selected but both controls lost their values on pageindexchanging event.
I want the checkbox to maintain its state and textbox to maintain whatever value user entered when the pageindexchanging event is called.
Here is the code to move to next page
protected void gvPayment_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvPayment.PageIndex = e.NewPageIndex;
GetCustomer();
}
Note: I have gone through all suggested similar questions with no luck or success.
You have to persist them, for example by storing a Disctionary<int, bool> in the ViewState where the key is the RowIndex and the value is the bool(CheckBox is Checked?):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["EnabledAmtPaidTextBoxes"] = new Dictionary<int, bool>();
GetCustomer();
}
}
I would encapsulate this logic in a method, you need to call it from RowDataBound and CheckedChanged. You don't need that final loop in GetCustomer anymore:
protected void gvPayment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
EnabledAmtPaidTextBox(e.Row);
}
}
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkSelect.NamingContainer;
EnabledAmtPaidTextBox(row, chkSelect.Checked);
}
private void EnabledAmtPaidTextBox(GridViewRow row, bool? newCheckedOrApplyOld = null)
{
TextBox AmtPaid = (TextBox)row.FindControl("AmtPaid");
Label AmtDue = (Label)row.FindControl("AmtDue");
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
Dictionary<int, bool> enabledAmtPaidTextBoxes = (Dictionary<int, bool>)ViewState["EnabledAmtPaidTextBoxes"];
if (!enabledAmtPaidTextBoxes.ContainsKey(row.RowIndex))
enabledAmtPaidTextBoxes[row.RowIndex] = false;
if (newCheckedOrApplyOld.HasValue)
enabledAmtPaidTextBoxes[row.RowIndex] = newCheckedOrApplyOld.Value;
else
chkSelect.Checked = enabledAmtPaidTextBoxes[row.RowIndex];
if (enabledAmtPaidTextBoxes[row.RowIndex])
{
AmtPaid.Text = AmtDue.Text.Replace(",", "");
AmtPaid.Attributes.Remove("readonly");
}
else
{
AmtPaid.Text = string.Empty;
AmtPaid.Attributes.Add("readonly", "readonly");
}
}
Also, if you use the using-statement you don't need con.Close and con.Dispose in finally because that is done by the using-statement already.

Column 'ID' does not belong to table DefaultView

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;
}
}

ASP.NET GridView: How to edit and delete data records

Hi I have used gridview to create a table.
Is there a way to implement edit and delete.
I have done it in PHP before. The method I would like to use is create two more columns in the table with edit and delete buttons on each row. Then when the buttons are click it passes the 'id' through the URL and able to edit or delete. Not really sure how to do this in asp.net webforms. Below is my code for the table. Thank you.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
<asp:BoundField HeaderText="PatientID" DataField="patientID" />
<asp:BoundField HeaderText="Location" DataField="location" />
</Columns>
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
The GridView supports those operations. You can add a CommandField which will contain the command buttons or LinkButtons (you can choose the type of button and assign the text of each button). The patientID field should be included in the DataKeyNames property of the GridView, in order to retrieve it when the time comes to update or delete the record in the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="patientID"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" />
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
...
</Columns>
You will then need to handle a few events in code-behind:
// The RowEditing event is called when data editing has been requested by the user
// The EditIndex property should be set to the row index to enter edit mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
// The RowCancelingEdit event is called when editing is canceled by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
// The RowUpdating event is called when the Update command is selected by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
string surgery = (string)e.NewValues["surgery"];
string location = (string)e.NewValues["location"];
// Update here the database record for the selected patientID
GridView1.EditIndex = -1;
BindData();
}
// The RowDeleting event is called when the Delete command is selected by the user
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
// Delete here the database record for the selected patientID
BindData();
}
Since the data must be bound to the GridView at the end of each of those event handlers, you can do it in a BindData utility function, which should also be called when the page loads initially:
private void BindData()
{
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
And Store Procedure is:
USE [DemoProjet]
GO
/****** Object: StoredProcedure [dbo].[Customers_CRUD] Script Date: 11-Jan-17 2:57:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Customers_CRUD]
#Action VARCHAR(10)
,#BId INT = NULL
,#Username VARCHAR(50) = NULL
,#Provincename VARCHAR(50) = NULL
,#Cityname VARCHAR(50) = NULL
,#Number VARCHAR(50) = NULL
,#Name VARCHAR(50) = NULL
,#ContentType VARCHAR(50) = NULL
,#Data VARBINARY(MAX) = NULL
AS
BEGIN
SET NOCOUNT ON;
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT BId , Username,Provincename,Cityname,Number,Name,ContentType, Data
FROM tblbooking
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO tblbooking(Username,Provincename,Cityname,Number,Name,ContentType, Data)
VALUES (#Username ,#Provincename ,#Cityname ,#Number ,#Name ,#ContentType ,#Data)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE tblbooking
SET Username = #Username,Provincename = #Provincename,Cityname = #Cityname,Number = #Number,Name = #Name,ContentType = #ContentType,Data = #Data
WHERE BId = #BId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM tblbooking
WHERE BId = #BId
END
END
GO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace FinalYearProject
{
public partial class MBooking : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void Insert(object sender, EventArgs e)
{
string Username = txtUsername.Text;
string Provincename = txtProvinceName.Text;
string Cityname = txtCityname.Text;
string Number = txtNumber.Text;
string Name = txtName.Text;
string ContentType = txtContentType.Text;
string Data = txtData.Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "INSERT");
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType", ContentType);
//cmd.Parameters.AddWithValue("#Data", Data);
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Username = (row.FindControl("txtUserName") as TextBox).Text;
string Provincename = (row.FindControl("txtProvincename") as TextBox).Text;
string Cityname = (row.FindControl("txtCityname") as TextBox).Text;
string Number = (row.FindControl("txtNumber") as TextBox).Text;
string Name = (row.FindControl("txtName") as TextBox).Text;
string ContentType = (row.FindControl("txtContentType") as TextBox).Text;
string Data = (row.FindControl("txtData") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "UPDATE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType",ContentType) ;
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
//cmd.Parameters.AddWithValue("#ContentType", SqlDbType.VarBinary, -1);
//cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary, -1);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
//{
// (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
//}
}
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=#BId";
cmd.Parameters.AddWithValue("#BId",id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "DELETE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
}
}
And Aspx page is:
<%# Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
<%-- body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th
{
background-color: #B8DBFD;
color: #333;
font-weight: bold;
}
table th, table td
{ background-color: #B8DBFD;
padding: 5px;
border: 1px solid #ccc;
}
table, table table td
{
border: 3px solid #ccc;
}
--%>
.style1
{
width: 184px;
}
</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
OnPageIndexChanging="OnPageIndexChanging" PageSize="6" DataKeyNames="BId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting"
EmptyDataText="No records has been added."
Style="margin:20px 0px 0px 25px;" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="250px"
Width="1035px" >
<Columns>
<asp:TemplateField HeaderText="Username" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUsername" style = "Width:100px;" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProvinceName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblProvinceName" runat="server" Text='<%# Eval("Provincename") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProvinceName" style = "Width:100px;" runat="server" Text='<%# Eval("Provincename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="CityName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblCityname" runat="server" Text='<%# Eval("Cityname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCityname" style = "Width:100px;" runat="server" Text='<%# Eval("Cityname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Number" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNumber" style = "Width:100px;" runat="server" Text='<%# Eval("Number") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Name" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" style = "Width:100px;" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="ContentType" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblContentType" runat="server" Text='<%# Eval("ContentType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContentType" style = "Width:100px;" runat="server" Text='<%# Eval("ContentType") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Data" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblData" runat="server" Text='<%# Eval("Data") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtData" style = "Width:100px;" runat="server" Text='<%# Eval("Data") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField> <ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("BId") %>'></asp:LinkButton>
</ItemTemplate></asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Center"
Font-Bold="True" Font-Italic="True" Font-Underline="True" Width="20px" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<br />
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; margin:10px 0px 0px 25px;">
<tr>
<td style="width: 100px; background-color:#003399; color:#CCCCFF;">
<b> Username:</b><br />
<asp:TextBox ID="txtUsername" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Provincename:</b><br />
<asp:TextBox ID="txtProvinceName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Cityname:</b><br />
<asp:TextBox ID="txtCityname" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Number:</b><br />
<asp:TextBox ID="txtNumber" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Name:</b><br />
<asp:TextBox ID="txtName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> ContentType:</b><br />
<asp:TextBox ID="txtContentType" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Data:</b><br />
<asp:TextBox ID="txtData" runat="server" Width="120" />
</td>
<td style="background-color:#003399; color:#CCCCFF;" class="style1">
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-info" Text="Add"
OnClick="Insert" Width="187px" />
</td>
</tr>
</table>
</asp:Content>

Loop through checkboxes in listview control to Update Database

Below is my ASP.net code with my Listview Control with a checkbox absentCheckBox
<asp:ListView ID="student_list" runat="server" DataSourceID="view_students">
<ItemTemplate>
<tr style="">
<td>
<asp:Label Text='<%# Eval("assignment_id") %>' runat="server" ID="assignment_idLabel" />
</td>
<td>
<asp:Label Text='<%# Eval("user_id") %>' runat="server" ID="user_idLabel" />
</td>
<td>
<asp:TextBox Text='<%# Eval("result_percentage") %>' runat="server" ID="result_percentageTextBox" />
</td>
<td>
<asp:CheckBox Checked='<%# Eval("absent") %>' runat="server" ID="absentCheckBox" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:Button ID="add_results" runat="server" Text="Update Results" OnClick="add_results_Click" CssClass="blue" />
Below is my C# code behind where I am trying to loop through the checkboxes in
protected void add_results_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in student_list.Items)
{
int student_id = 0;
Label student_id_lbl = (Label)item.FindControl("user_idLabel");
student_id = Convert.ToInt32(student_id_lbl.Text);
int assignment_id = 0;
Label assignment_id_lbl = (Label)item.FindControl("assignment_idLabel");
assignment_id = Convert.ToInt32(assignment_id_lbl.Text);
int result = 0;
TextBox result_total_ddl = item.FindControl("result_percentageTextBox") as TextBox;
if (result_total_ddl != null)
{
if (Int32.TryParse(result_total_ddl.Text, out result))
{
}
else
{
}
}
bool absent = false;
CheckBox absent_chk = item.FindControl("absentCheckBox") as CheckBox;
absent = Convert.ToBoolean(absent_chk.Text);
if (result < 0 || result > 100)
{
feedback.Text = "Please enter an assignment total in between 0 - 100 you have entered : <b>" + result + "</b>.";
}
else
{
String connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(connectionString);
myConnection.Open();
String query = "UPDATE assignments_vs_users SET result_percentage = #result_percentage, absent = #absent WHERE assignment_id = #assignment_id AND user_id = #student_id; ";
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#result_percentage", result);
myCommand.Parameters.AddWithValue("#assignment_id", assignment_id);
myCommand.Parameters.AddWithValue("#student_id", student_id);
myCommand.Parameters.AddWithValue("#absent", absent);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
How can I use absent within myCommand.Parameters.AddWithValue("#absent", absent); so it updates the database column for absent if the checkbox is ticked to true

When I update date from gridview, the date and month will always switch places. I want it to be dd/mm/yyyy format

I edit and changed the dateentry for the first row from 05/04/2014 to 06/04/2014. After clicking update, it becomes 04/06/2014. My dateEntry column is a date type format and not a datetime format for your information. I want it to be dd/mm/yyyy format.
If I put anything higher than 12 in the date. etc 16. will have error.
Error following #Arshad advice
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
bindResultGridView();
}
//Logout.Visible = false;
string memName = (String)Session["UserName"];
lblUsername.Text = String.Concat("Welcome Guest!");
if (Session["Username"] != null && Session["Username"] != String.Empty)
{
lblUsername.Text = "Welcome, " + memName + "!";
}
}
private void bindResultGridView()
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
String SQL = null;
SQL = "SELECT BlogID, Name, Blogtype, Description, Dateentry FROM [EntryTable]";
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdBlog.DataSource = dt;
grdBlog.DataBind();
reader.Close();
}
finally
{
con.Close();
}
}
protected void grdBlog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdBlog.EditIndex = -1;
bindResultGridView();
}
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
TextBox blogtype = (TextBox)row.FindControl("txtBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox dateentry = (TextBox)row.FindControl("txtDateEntry");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strDateEntry = dateentry.Text;
DateTime datDate;
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, datDate.ToString());
}
else
{
}
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, string strDateEntry)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry WHERE [BlogID]=#BlogID";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
cmd.Parameters.AddWithValue("#DateEntry", strDateEntry);
cmd.Parameters.AddWithValue("#Description", strDescription);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblError.Text = "Record updated!";
}
else
{
lblError.Text = "Update fail";
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
Source code
<asp:GridView ID="grdBlog" runat="server" style=
"margin-left: 0px" Width="695px" Height="147px" AutoGenerateColumns="False"
onrowcancelingedit="grdBlog_RowCancelingEdit" onrowediting="grdBlog_RowEditing"
onrowupdating="grdBlog_RowUpdating" DataKeyNames="BlogID"
onrowdeleting="grdBlog_RowDeleting" AllowPaging="True"
onpageindexchanging="grdBlog_PageIndexChanging" PageSize="5">
<Columns>
<asp:BoundField DataField="BlogID" HeaderText="BlogID"
SortExpression="BlogID" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:TextBox ID="txtBlogType" runat="server" Text='<%# Bind("BlogType") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DateEntry">
<EditItemTemplate>
<asp:TextBox ID="txtDateEntry" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="javascript : return confirm('Confirm delete this record?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Followed #Chirag Adhvaryu This worked for me.
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
TextBox blogtype = (TextBox)row.FindControl("txtBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox dateentry = (TextBox)row.FindControl("txtDateEntry");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strDateEntry = dateentry.Text;
DateTime datDate;
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, datDate);
}
else
{
}
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, DateTime datDate)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry WHERE [BlogID]=#BlogID";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
cmd.Parameters.AddWithValue("#DateEntry", datDate);
cmd.Parameters.AddWithValue("#Description", strDescription);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblError.Text = "Record updated!";
}
else
{
lblError.Text = "Update fail";
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
You can try like this.
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# Eval("Date", "{0:dd/MM/yyyy}")%>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Update your DateEntry template field with '<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>' instead of '<%# Bind("DateEntry") %>'
<asp:TemplateField HeaderText="DateEntry">
<EditItemTemplate>
<asp:TextBox ID="txtDateEntry" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("DateEntry", "{0:dd/MM/yyyy}") %>'></asp:Label>
</ItemTemplate>
Edit
string strDate = dateentry.Text;
DateTime datDate;
if(DateTime.TryParseExact(strDate , new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
// Call your update method with
}
else
{
//Show validation error message
}
You can validate Date Time like this on client side.
<asp:TemplateField HeaderText="date" SortExpression="date">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("date") %>'></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" BackColor="Red" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Invalid Date" MaximumValue="28/12/9999" MinimumValue="28/12/1000" SetFocusOnError="True" Type="Date"></asp:RangeValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# Eval("date", "{0:dd/MM/yyyy}")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />

Categories

Resources