Rebind a GridView Datasource after editing a Textbox in the ItemTemplate - c#

I have a DataGrid with a datasource on page load, but when I make changes to the Textboxes within the datagrid, I don't know how to get those new textbox.text.
I don't what to change the new datasource to??
So My question is how Do I update the datasource and save my new edited TextBox.Text field??...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
CustomerDao dao = new CustomerDao();
currentCustomer = dao.SelectAll().First(x => x.CustomerID == 3) as Customer;
//Assigning SQL Datasource to Gridview
SqlDataSource1.SelectCommand = "SELECT CustomerID, FirstName, MiddleIntial, LastName, DateOfBirth, TaxID, GenderId FROM Customer " +
"WHERE CustomerID = " + 3;
ClientGridView.DataBind();
}
protected void btnSave_Click(object sender, EventArgs e)
{
//Set a new datasource here??
string firstName = string.Empty;
string middileInitial = string.Empty;
string lastname = string.Empty;
string date = string.Empty;
DateTime dateOfBirth;
string taxId = string.Empty;
string strGender = string.Empty;
int genderId = 0;
foreach (GridViewRow r in ClientGridView.Rows)
{
firstName = ((TextBox)r.FindControl("txtFirstName")).Text;
middileInitial = ((TextBox)r.FindControl("txtMiddleInitial")).Text;
lastname = ((TextBox)r.FindControl("txtLastName")).Text;
date = ((TextBox)r.FindControl("txtDateOfBirth")).Text;
taxId = ((TextBox)r.FindControl("txtTaxID")).Text;
strGender = ((TextBox)r.FindControl("txtGenderID")).Text;
}
}
I have been searching for hours and found nothing really relating to my situation. I also feel like there should be a much better way then to implement all the event handlers for _RowEditing and _RowUpdating and I have tried these but none of their event handlers fired anyway....
EDIT: Heres my GridView XAML
<asp:GridView runat="server" ID="ClientGridView" AutoGenerateColumns="false" AllowPaging="true" AllowSorting="true" OnRowEditing="ClientGridView_RowEditing"
Width="650px" PageSize="20" CssClass="gridView" DataSourceID="SqlDataSource1" OnDataBound="ClientGridView_DataBound" >
<Columns>
<asp:TemplateField HeaderText="First Name" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtFirstName" Text='<%# Bind("FirstName") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Initial" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtMiddleInitial" Text='<%# Bind("MiddleIntial") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtLastName" Text='<%# Bind("LastName") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of birth" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDateOfBirth" Text='<%# Bind("DateOfBirth") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tax ID" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtTaxID" Text='<%# Bind("TaxID") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Gender ID" HeaderStyle-CssClass="headerStyle">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtGenderID" Text='<%# Bind("GenderId") %>' CssClass="txtStyle" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and the SQLDataSource
<asp:SqlDataSource ID="SqlDataSource1" runat="server" CancelSelectOnNullParameter="false"
ConnectionString=myconnectionString;User Id=userID;Password=pass; Persist Security Info=false;" />

Related

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

Using Dropdown List for options for Search function in ASP.NET

I did work on a Search function where the user can type the item they want to search on a textbox, then hit a button to search.
the Search function is already working but for one option only (ContractNo), now I like to add a Dropdown list to add more options for the users to search (add: EmpID, TrainingCode etc)
here is the code for the aspx: (yes i only just included the codes that I think is necessary)
<div id="contentarea">
<p> Search Employee ID, Training Code, Contract Number<br/>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Contract Number</asp:ListItem>
<asp:ListItem>Training Code</asp:ListItem>
<asp:ListItem>Employee ID</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="searchText" runat="server" Height="16px" Width="146px"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" />
<asp:Button ID="ButtonClear" runat="server" Text="Clear" OnClick="ButtonClear_Click" />
</p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="TrainingCode" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
</a>
</Itemtemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="ContractNo" SortExpression="ContractNo">
<ItemTemplate>
<asp:Label ID="LabelContractNo" Text='<% #HighlightText(Eval("ContractNo").ToString()) %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TrainingCode" SortExpression="TrainingCode">
<ItemTemplate>
<asp:Label ID="LabelTrainingCode" runat="server" Text='<%# Eval("TrainingCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmpID" SortExpression="EmpID">
<ItemTemplate>
<asp:Label ID="LabelEmpID" runat="server" Text='<%# Eval("EmpID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContractDate" SortExpression="ContractDate">
<ItemTemplate>
<asp:Label ID="LabelContractDate" runat="server" Text='<%# Eval("ContractDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContractDuration" SortExpression="ContractDuration">
<ItemTemplate>
<asp:Label ID="LabelContractDuration" runat="server" Text='<%# Eval("ContractDuration") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ServiceStart" SortExpression="ServiceStart">
<ItemTemplate>
<asp:Label ID="LabelServiceStart" runat="server" Text='<%# Eval("ServiceStart") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ContractValue" SortExpression="ContractValue">
<ItemTemplate>
<asp:Label ID="LabelContractValue" runat="server" Text='<%# Eval("ContractValue") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Served" SortExpression="Served">
<ItemTemplate>
<asp:Label ID="LabelServed" runat="server" Text='<%# Bind("Served") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbx %>" DeleteCommand="DELETE FROM [SCHOLARSHIPCONTRACT] WHERE [TrainingCode] = #TrainingCode" InsertCommand="INSERT INTO [SCHOLARSHIPCONTRACT] ([ContractNo], [TrainingCode], [EmpID], [ContractDate], [ContractDuration], [ServiceStart], [ContractValue], [Served]) VALUES (#ContractNo, #TrainingCode, #EmpID, #ContractDate, #ContractDuration, #ServiceStart, #ContractValue, #Served)" SelectCommand="SELECT * FROM [SCHOLARSHIPCONTRACT]" UpdateCommand="UPDATE [SCHOLARSHIPCONTRACT] SET [ContractNo] = #ContractNo, [EmpID] = #EmpID, [ContractDate] = #ContractDate, [ContractDuration] = #ContractDuration, [ServiceStart] = #ServiceStart, [ContractValue] = #ContractValue, [Served] = #Served WHERE [TrainingCode] = #TrainingCode" FilterExpression="ContractNo '%{0}%'">
<FilterParameters>
<asp:ControlParameter Name="ContractNo" ControlID="searchText" PropertyName="Text"/>
</FilterParameters>
</asp:SqlDataSource>
and the FULL C# backend code:
private string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
}
public string HighlightText(string InputText)
{
string Search_str = searchText.Text;
Regex RegExp = new Regex(Search_str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
return RegExp.Replace(InputText, new MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(Match m) //this is just to highlight the item searched
{
return ("<span class=highlight>" + m.Value + "</span>");
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SearchString = searchText.Text;
}
protected void ButtonClear_Click(object sender, EventArgs e)
{
searchText.Text = "";
SearchString = "";
GridView1.DataBind();
}
Now im thinking to add an if statement maybe? on the FilterParameters? like
<% if (DropDownList1.text == "EmpID"){}
but Im not sure.. Can you suggest other methods please?? Let me know if you might need other codes from the program. Thank you in advance
Try to use generic options. Use DropDown to list all types (EmpID, TrainingCode). On the basis of type selection use Switch to filter by entered text in TextBox.
SearchString = searchText.Text;
Switch(types)
{
case EmpID:
DoOperation();
break;
case TrainingCode:
DoOperation();
break;
}
Ok , here the solution, it's working ok in my computer, I hope this is what you want to achieve. I put some comments in the code, read them
in aspx page , put this code
<div id="contentarea">
<p> Search Employee ID, Training Code, Contract Number<br/>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="ContractNo">Contract Number</asp:ListItem>
<asp:ListItem Value="TrainingCode">Training Code</asp:ListItem>
<asp:ListItem Value="EmpID">Employee ID</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="searchText" runat="server" Height="16px" Width="146px"></asp:TextBox>
<asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" />
<asp:Button ID="ButtonClear" runat="server" Text="Clear" OnClick="ButtonClear_Click" />
</p>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
and this is the C# code in aspx.cs
private string SearchString = "";
protected void Page_Load(object sender, EventArgs e)
{
}
public string HighlightText(string InputText)
{
string Search_str = searchText.Text;
Regex RegExp = new Regex(Search_str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase);
return RegExp.Replace(InputText, new MatchEvaluator(ReplaceKeywords));
}
public string ReplaceKeywords(Match m) //this is just to highlight the item searched
{
return ("<span class=highlight>" + m.Value + "</span>");
}
private DataTable GetData(string query)
{
// Read connection string from web.config file , Important, change the
//ConnectionStrings name here (testConnectionString)
// and replace it with your connection name , you can find it in web.config file
// in <connectionStrings> tag , you find it after this tag <add name="
string CS = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter sda = new SqlDataAdapter(query, con);
using (DataTable dt = new DataTable())
{
con.Open();
sda.Fill(dt);
return dt;
}
}
}
protected void ButtonSearch_Click(object sender, EventArgs e)
{
SearchString = searchText.Text;
string columnName = DropDownList1.SelectedValue;
string searchSQL = "SELECT * FROM [SCHOLARSHIPCONTRACT] WHERE " + columnName + "= '" + SearchString + "'";
//bind the SCHOLARSHIPCONTRACT table data into GridView1
DataTable dt = this.GetData(searchSQL);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void ButtonClear_Click(object sender, EventArgs e)
{
searchText.Text = "";
SearchString = "";
GridView1.DataBind();
}

disable textbox in edit mode

i have a edit function in my gridview. however what i want to do is to disable the visibility of the textbox when i click on update function on a specific data bound. here is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductID"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ProductName") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Invalid" ForeColor="Red" ControlToValidate="txtboxProductName"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductDescription">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtboxProductDescription" runat="server" Text='<%# Bind("ProductDescription") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="Invalid"
ForeColor="Red" ControlToValidate="txtboxProductDescription"
ValidationExpression="^[a-zA-Z ]+$"></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText ="ProductImage" DataImageUrlField="ProductImage" SortExpression="ProductImage" ControlStyle-Width ="10">
<ControlStyle Width="50px"></ControlStyle>
</asp:ImageField>
<asp:TemplateField HeaderText="ProductQuantity">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtboxProductQuant" runat="server" Text='<%# Bind("ProductQuantity") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ErrorMessage="Invalid" ControlToValidate="txtboxProductQuant"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductPrice">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtboxProductPrice" runat="server" Text='<%# Bind("ProductPrice") %>'></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ErrorMessage="Invalid" ControlToValidate="txtboxProductPrice"
ForeColor="Red" ValidationExpression=^[0-9]*$></asp:RegularExpressionValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
<%--<asp:CommandField ShowDeleteButton="true" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete"
OnClientClick="return confirm('Confirm Delete?');"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my update code behind:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Finding the controls from Gridview for the row which is going to update
//Label id = GridView1.Rows[e.RowIndex].FindControl("lbl_ID") as Label;
int userid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox ProductName = GridView1.Rows[e.RowIndex].FindControl("txtboxProductName") as TextBox;
TextBox ProductDescription = GridView1.Rows[e.RowIndex].FindControl("txtboxProductDescription") as TextBox;
TextBox ProductQuantity = GridView1.Rows[e.RowIndex].FindControl("txtboxProductQuant") as TextBox;
TextBox ProductPrice = GridView1.Rows[e.RowIndex].FindControl("txtboxProductPrice") as TextBox;
conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=Authorship;Integrated Security =True");
conn.Open();
//updating the record
SqlCommand cmd = new SqlCommand("Update Products set ProductName='" + ProductName.Text + "',ProductDescription='" + ProductDescription.Text + "',ProductQuantity='" + ProductQuantity.Text + "', ProductPrice='" + ProductPrice.Text + "' where ProductID='" + userid + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Setting the EditIndex property to -1 to cancel the Edit mode in Gridview
GridView1.EditIndex = -1;
//Call ShowData method for displaying updated data
gvbind();
}
i don't have the product image inside a edit template and also, product image is not included in my code behind. cant understand why a text box becomes visible on product image when i click on update function. please help.
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
for example
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Handles GridView1.RowDataBound
If e.Row.RowState = DataControlRowState.Edit Then
ctype(e.Row.Cells(1).Controls(0),TextBox).Enabled=False
End If
End Sub

How to Store SelectedRow.Cell[0] value in a session when CommandField is "Select" in a GridView

How to Store SelectedRow.Cell[0] value in a session when CommandField is "Select" in a GridView. ? What the changes i will do in my code so that when a Select Command executes on my grid (By Clicking on Select Link of my grid), It will Store the NatureOfWorkID of that row in the session variable. Below is my code. Please guide me that what changes required in the below code so that when ever some one will click on Select, the natureofworkID of that row will be stored in a Session and i will bind another grid from the session variable as per my requirement.
<asp:GridView ID="GVNatureOFWork" runat="server" AllowPaging="true" ShowFooter="true" PageSize="10" AutoGenerateColumns="false"
DataKeyNames="NatureOfWorkID"
OnPageIndexChanging="GVNatureOFWork_PageIndexChanging"
onrowcancelingedit="GVNatureOFWork_RowCancelingEdit"
onrowcommand="GVNatureOFWork_RowCommand" onrowdeleting="GVNatureOFWork_RowDeleting"
onrowediting="GVNatureOFWork_RowEditing" onrowupdating="GVNatureOFWork_RowUpdating"
OnSelectedIndexChanged="GVNatureOFWork_SelectedIndexChanged" OnRowDataBound="GVNatureOFWork_RowDataBound"
HeaderStyle-BackColor="BlueViolet"
HeaderStyle-ForeColor="White" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="NatureOfWorkID">
<ItemTemplate>
<asp:Label ID="lblNautureOfWorkID" runat="server" Text='<%#Eval("NatureOfWorkID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nature of Work Name">
<ItemTemplate>
<asp:Label ID="lblNatureOfWorkName" runat="server" Text='<%#Eval("NatureOfWorkName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNatureOfWorkName" runat="server" Text='<%#Eval("NatureOfWorkName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddNatureOfWorkName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Enable/Disable">
<ItemTemplate>
<asp:Label ID="lblNOWStatus" runat="server" Text='<%# (int)Eval("IsNOWEnabled") == 1 ? "Enabled" : "Disabled" %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="radiolistStatus" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="radiolistStatusAdd" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField ShowSelectButton="True" ItemStyle-CssClass="HiddenColumn" HeaderStyle-CssClass="HiddenColumn"/>
</Columns>
</asp:GridView><br /><br /><br /><br />
<asp:GridView ID="GVRegionProject" runat="server" AllowPaging="true" ShowFooter="true" PageSize="10" AutoGenerateColumns="false"
OnPageIndexChanging="GVRegionProject_PageIndexChanging"
onrowcancelingedit="GVRegionProject_RowCancelingEdit"
onrowcommand="GVRegionProject_RowCommand" onrowdeleting="GVRegionProject_RowDeleting"
onrowediting="GVRegionProject_RowEditing" onrowupdating="GVRegionProject_RowUpdating"
OnSelectedIndexChanged="GVRegionProject_SelectedIndexChanged"
HeaderStyle-BackColor="BlueViolet"
HeaderStyle-ForeColor="White" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="Region/Project ID">
<ItemTemplate>
<asp:Label ID="lblRegionProjectID" runat="server" Text='<%#Eval("RegionProjectID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Region/Project Name">
<ItemTemplate>
<asp:Label ID="lblRegionProjectName" runat="server" Text='<%#Eval("RegionProjectName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRegionProjectName" runat="server" Text='<%#Eval("RegionProjectName") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddRegionProjectName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Enable/Disable">
<ItemTemplate>
<asp:Label ID="lblRPStatus" runat="server" Text='<%# (int)Eval("IsRegionProjectEnabled") == 1 ? "Enabled" : "Disabled" %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="radiolistStatus" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="radiolistStatusAdd" runat="server">
<asp:ListItem Text="Enable" Value="1"></asp:ListItem>
<asp:ListItem Text="Disable" Value="0"></asp:ListItem>
</asp:RadioButtonList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="AddNew" Text="Add New"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="County" ShowHeader="false" ShowSelectButton="True"/>
</Columns>
</asp:GridView>
Code Behind is :-
private void BindGrid()
{
dataTable = new DataTable();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM natureOfWork";
ad = new SqlDataAdapter(cmd);
ad.Fill(dataTable);
GVNatureOFWork.DataSource = dataTable;
GVNatureOFWork.DataBind();
}
protected void GVNatureOFWork_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GVNatureOFWork.PageIndex = e.NewPageIndex;
BindGrid();
}
protected void GVNatureOFWork_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GVNatureOFWork.EditIndex = -1;
BindGrid();
}
protected void GVNatureOFWork_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtAddNatureOfWorkName = (TextBox)GVNatureOFWork.FooterRow.FindControl("txtAddNatureOfWorkName");
RadioButtonList radiolistStatusAdd = (RadioButtonList)GVNatureOFWork.FooterRow.FindControl("radiolistStatusAdd");
if ((txtAddNatureOfWorkName.Text != "")&&(radiolistStatusAdd.SelectedValue != string.Empty))
{
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO NatureOFWork(NatureOFWorkname, isNOWEnabled ) Values('" + txtAddNatureOfWorkName.Text + "', '" + radiolistStatusAdd.SelectedValue.ToString() + "')";
conn.Open();
cmd.ExecuteNonQuery();
}
BindGrid();
conn.Close();
}
if (e.CommandName.Equals("Select"))
{
}
}
protected void GVNatureOFWork_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblNautureOfWorkID = (Label)GVNatureOFWork.Rows[e.RowIndex].FindControl("lblNautureOfWorkID");
cmd.Connection = conn;
cmd.CommandText = "DELETE FROM NatureOFWork WHERE NatureOfWorkID='" + lblNautureOfWorkID.Text.ToString() + "'";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindGrid();
}
protected void GVNatureOFWork_RowEditing(object sender, GridViewEditEventArgs e)
{
GVNatureOFWork.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GVNatureOFWork_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblNautureOfWorkID = (Label)GVNatureOFWork.Rows[e.RowIndex].FindControl("lblNautureOfWorkID");
TextBox txtNatureOfWorkName = (TextBox)GVNatureOFWork.Rows[e.RowIndex].FindControl("txtNatureOfWorkName");
RadioButtonList radiolistStatus = (RadioButtonList)GVNatureOFWork.Rows[e.RowIndex].FindControl("radiolistStatus");
string isenabled = radiolistStatus.SelectedValue.ToString();
cmd.Connection = conn;
cmd.CommandText = "UPDATE NatureOfWork SET NatureOfWorkname ='" + txtNatureOfWorkName.Text + "',IsNowEnabled=" + isenabled.ToString() + " WHERE NatureOFWorkID=" + lblNautureOfWorkID.Text.ToString();
conn.Open();
cmd.ExecuteNonQuery();
GVNatureOFWork.EditIndex = -1;
BindGrid();
conn.Close();
}
protected void GVNatureOFWork_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblNautureOfWorkID = (Label)e.Row.FindControl("lblNautureOfWorkID");
Label lblNatureOfWorkName = (Label)e.Row.FindControl("lblNatureOfWorkName");
TextBox txtNatureOfWorkName = (TextBox)e.Row.FindControl("txtNatureOfWorkName");
TextBox txtAddNatureOfWorkName = (TextBox)e.Row.FindControl("txtAddNatureOfWorkName");
RadioButtonList radiolistStatusAdd = (RadioButtonList)e.Row.FindControl("radiolistStatusAdd");
RadioButtonList radiolistStatus = (RadioButtonList)e.Row.FindControl("radiolistStatus");
Label lblNOWStatus = (Label)e.Row.FindControl("lblNOWStatus");
}
if (e.Row.RowType == DataControlRowType.Footer)
{
}
}
protected void GVNatureOFWork_SelectedIndexChanged(object sender, EventArgs e)
{
string natureOfWorkID=GVNatureOFWork.SelectedRow.Cells[0].Text;
BindRegionProjectInfoGrid();
}
Your code editted :
(e.CommandName.Equals("Select"))
{
Label lblNautureOfWorkID = (Label)GVNatureOFWork.SelectedRow.FindControl("lblNautureOfWorkID");
if(lblNautureOfWorkID != null)
{
string natureofworkID = lblNautureOfWorkID.Text.ToString();
}
}
protected void GVNatureOFWork_SelectedIndexChanged(object sender, EventArgs e)
{
int index = GVNatureOFWork.SelectedIndex;
string natureofwrkid = GVNatureOFWork.DataKeys[index].Value.ToString();
Session["NOWID"] = natureofwrkid;
lblDisplayNOWID.Text = natureofwrkid;
BindRegionProjectInfoGrid();
}
By adding these lines, Now i am able to get Cell[0] value of the selected row in my grid. Thanks To every one for guiding me to get the solution.

Trying to Add Insert Row to Footer in GridView ASP.net

I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>
I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="name" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.
A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}

Categories