Bind data to nested grid in footer - c#

I have added programatically button to the footer in RowDataBound:
else if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Text = "Total: ";
e.Row.Cells[2].Text = totalStaff.ToString();
Button showStaff = new Button();
showStaff.CommandName = "ShowAll";
showStaff.Text = e.Row.Cells[2].Text.ToString();
e.Row.Cells[2].Controls.Add(showStaff);
e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Right;
showStaff.Click += new EventHandler(showStaff_Click);
}
now I want to handle showStaff_Click to bind data to nested gridview. I wrote bwlow code in RowCommand but index is null:
if(e.CommandName == "ShowAll")
{
int index = Convert.ToInt32(e.CommandArgument.ToString());
GridViewRow row = Staff.Rows[index];
GridView StaffInfo = (GridView)Staff.Rows[index].FindControl("StaffInfo");
int TeamID = 0;
int cityID = 3699;
StaffInfo.DataSource = GetStaff(cityID, TeamID);
StaffInfo.DataBind();
}
I will appreciate Your help.
EDIT:
I have nade some changes:
protected void Staff_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//Checking for command name which command/button is pressed
if (e.CommandName == "ShowDetails")
{
GridView Staff = (GridView)sender;
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Staff.Rows[index];
GridView StaffInfo = (GridView)Staff.Rows[index].FindControl("StaffInfo");
int TeamID = Convert.ToInt16(Staff.DataKeys[index].Values[0].ToString());
int cityID = Convert.ToInt16(Staff.DataKeys[index].Values[1].ToString());
StaffInfo.DataSource = GetStaff(cityID, TeamID);
StaffInfo.DataBind();
StaffInfo.Visible = true;
}
else if(e.CommandName == "ShowAll")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView StaffInfo = (GridView)Staff.Rows[index].FindControl("StaffInfo");
int TeamID = 0;
int cityID = 3699;
StaffInfo.DataSource = GetStaff(cityID, TeamID);
StaffInfo.DataBind();
StaffInfo.Visible = true;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
<asp:GridView ID="Staff" runat="server" AutoGenerateColumns="false"
OnRowCommand="Staff_RowCommand"
DataKeyNames="TeamID,CityID" ShowFooter="True" HorizontalAlign="Center">
<Columns>
<asp:TemplateField HeaderText=" Function">
<ItemTemplate>
<asp:Label Width="150px" ID="Function" ItemStyle-HorizontalAlign="Center" runat="server" Text='<%# Bind("Function") %>'></asp:Label>
<asp:GridView ID="StaffInfo" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="FirstName" HeaderText="First Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="LastName" HeaderText="Last Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="SOEID" HeaderText="SOEID" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Team">
<ItemTemplate>
<asp:Label Width="150px" ID="Team" ItemStyle-HorizontalAlign="Center" runat="server" Text='<%# Bind("Team") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Staff Count">
<ItemTemplate>
<asp:Button Width="40px" ID="StaffCount" ItemStyle-HorizontalAlign="Center" runat="server" Text='<%# Bind("StaffCount") %>' CommandName="ShowDetails" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" CausesValidation="True" UseSubmitBehavior="False" />
</ItemTemplate>
<FooterTemplate>
<asp:Button id="TotalStaff" runat="server" Text="Button1" CommandName="ShowAll" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CausesValidation="True" UseSubmitBehavior="False" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField Visible ="false">
<ItemTemplate>
<asp:Label runat="server" Width="150px" DataField="TeamID" HeaderText="TeamID" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible ="false">
<ItemTemplate>
<asp:Label runat="server" ItemStyle-Width="150px" DataField="CityID" HeaderText="CityID"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
When I try to click the ShowAll button ite returns that index is out of range. I made Response.Write(intex.ToString()) and it returns -1. The index number in case or row is returned correctly. The problem is with footer button. Could You please help me?

You did not set CommandArgument when you crated your button.
Button showStaff = new Button();
showStaff.CommandName = "ShowAll";
showStaff.CommandArgument = e.Row.RowIndex.ToString();
showStaff.Text = e.Row.Cells[2].Text.ToString();

Related

How can i hold gridview row selected values into a string in asp.net

I have gridview control it contains 6 columns when i click 6th column row of gridview i need to selecte that contains columns row text into a string. how can i take here i am taking commandargument is a string and how can i take another column names text
my code:
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:GridView ID="GridView1" Width="950px" CssClass="Grid" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="" ItemStyle-ForeColor="White" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="SName" HeaderText="SName" />
<asp:BoundField DataField="Date" HeaderText="Date" />
<asp:BoundField DataField="Size" HeaderText="Size(MB)" />
<asp:BoundField DataField="Time" HeaderText="Time" />
<asp:TemplateField HeaderText="FileName">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'
CommandName="Download" Text='<%# Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="S.No." Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string ID1;
if (e.CommandName == "Download")
{
GridViewRow gvr = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int rowIndex = gvr.RowIndex;
Label Itemid = (Label)GridView1.Rows[rowIndex].FindControl("lblID");
ID1 = (Itemid).Text;
Session["ID"] = ID1;
string filename = e.CommandArgument.ToString();
//here how can i hold another column text
}
}
I have a easiest way to do this same thing...
<asp:Label ID="lblName" runat="server" Text='<%#Eval("ID").ToString() +", "+ Eval("OtherCoulmn").ToString() %>'></asp:Label>
--- hope it helps
Also the best way is to do something like this
((MyObject)Container.DataItem).MyProperty where MyObject is the Model which you bind with grid and property which you wan to use in rowcommand its clean .
Simply follow the bellow code sample:
protected void btnEdit_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
Label lblId = gvCipamMember.Rows[gvr.RowIndex].FindControl("lblPersonId") as Label;
cmd = new SqlCommand("SELECT Id,Res_Person,Email_ID,Mobile_NO,Cipam_Flag FROM Responsibilty_Master WHERE Id=#Id", con.MyConnection);
cmd.Parameters.AddWithValue("#Id", Convert.ToInt32(lblId.Text.ToString()));
dt = new DataTable();
con.MyConnection.Open();
dt.Load(cmd.ExecuteReader());
if (dt.Rows.Count > 0)
{
txtPersonName.Text = dt.Rows[0]["Res_Person"].ToString();
txtEmail.Text = dt.Rows[0]["Email_ID"].ToString();
txtMobileNo.Text = dt.Rows[0]["Mobile_NO"].ToString();
if(Convert.ToBoolean(dt.Rows[0]["Cipam_Flag"].ToString())==true)
{
chkbCipamFlag.Checked = true;
}
}
}

finding label in itemTemplate and bind data from code behind

I wanted to display value in a label (label inside itemTemplate)
i have tried this approach
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
string LabelText = ((Label)row.FindControl("labelSelf")).Text;
LabelText = s;
Response.Write(LabelText+"test");
}
}
but nothing is shown in the label inside the gridview. IT should display the value of s.
Next approach was
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
Label labelSelfCollect = GridView1.FindControl("labelSelf") as Label;
labelSelfCollect.Text = "Self Collect at "+ s;
I got this error
System.NullReferenceException: Object reference not set to an instance of an object.
and the last approach that i have used is
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label labelcollect = row.FindControl("labelSelf") as Label;
labelcollect.Text = "self collect at "+ s;
}
}
}
using this method also it shows nothing.How should i assign the s value into this labelSelf(label inside itemTemplate)?
my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="772px" style="margin-left: 120px; text-align: left" Height="100px" DataKeyNames ="progressID" OnRowDataBound="GridView1_OnRowDataBound" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" CssClass="rounded_corners" HeaderStyle-Height="40px">
<AlternatingRowStyle CssClass="rounded_corners tr tr" />
<Columns>
<asp:BoundField ControlStyle-BorderWidth="60" DataField="dateupdate" HeaderText="Date Update" DataFormatString="{0:dd/MM/yyyy}" >
<ControlStyle BorderWidth="60px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Progress">
<ItemTemplate >
<%# Eval("message") %>
<br />
<asp:label ID="labelRemark" runat="server" style="Font-Size:11.5px;" text='<%# Eval("remark") %>'></asp:label><br />
<asp:Label ID="labelSelf" runat="server" style="Font-Size:11.5px;" ></asp:Label><br />
<div id="div<%# Eval("progressID") %>" >
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="progressID" style="text-align:center; font-size:small;" CellPadding="4" OnRowCommand="GridView2_RowCommand" GridLines="None" CssClass="rounded_corners" Width="500px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="tackingNo" HeaderText="Courier Tracking No" ItemStyle-Font-Size="Small" ItemStyle-Width="150px" >
</asp:BoundField>
<asp:BoundField DataField="courierDate" HeaderText="Courier Date">
</asp:BoundField>
<asp:TemplateField HeaderText="Provider">
<ItemTemplate>
<asp:HyperLink Text='<%#Eval("providernm")%>' Target="_blank" runat="server" DataNavigateUrlFields="companyurl" NavigateUrl='<%#Eval("companyurl")%>' ></asp:HyperLink>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tracking" >
<ItemTemplate>
<br />
<asp:HyperLink Text="Track Here" Target="_blank" runat="server" DataNavigateUrlFields="trackingurl" NavigateUrl='<%#Eval("trackingurl")%>' ></asp:HyperLink>
<br />
<asp:Label ID="Label4" runat="server" Text="* check after 24 hours" Font-Italic="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonDELETE" runat="server" CommandName="Delete" Text="Delete" OnClientClick= "return confirm('Confirm Delete progress?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Thank you.
Use GridView1_OnRowDataBound instead of foreach (GridViewRow row in GridView1.Rows). Apart from that your first approach is correct. You're simply not assigning the Text property there but reading from it.
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label labelSelf = (Label)e.Row.FindControl("labelSelf");
labelSelf.Text = address.getSelfCollectAddress(orderNoTracking); // maybe you need to retrieve the orderNoTracking from another control in this row or from it's datasource
}
}

Remove Hyperlink of specif cell in gridview

I've created a gridview, which all values (footer included) are hyperlinks, to export a detail in Excel.
All is working fine, except, when the value is 0, I don't want to permit the hyperlink, so it doesn't create a empty excel.
<asp:GridView ID="dtlist" runat="server" CellPadding="0" CssClass="table tabela caixa " CellSpacing="0" OnRowDataBound="dtlist_RowDataBound" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="true" >
<Columns >
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="LabelT" runat="server" Text="Total"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:HyperLink runat="server" ID="lnkA" NavigateUrl='<%# String.Format("/Export?name={0}, Eval("name")) %>' Text='<%# Eval("value","{0:#####,##0.00 €}") %>' />
<asp:Label runat="server" ID="lblA" Text='<%# Eval("value","{0:#####,##0.00 €}") %>' Visible="false" />
</ItemTemplate>
<ItemStyle CssClass="alinha-direita" />
<FooterTemplate>
<asp:HyperLink runat="server" ID="lnkTA" />
</FooterTemplate>
<FooterStyle CssClass="alinha-direita" />
<HeaderStyle CssClass="alinha-meio" />
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the RowDataBound:
protected void dtlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Total = 0;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hA = (HyperLink)e.Row.FindControl("lnkA");
Label lA = (Label)e.Row.FindControl("lblA");
if (hA.Text.ToDecimal() == 0)
{
hA.Visible = false;
lA.Visible = true;
}
Total += ((DataRowView)e.Row.DataItem).Row["Ano0"].ToDecimal();
}
if (e.Row.RowType == DataControlRowType.Footer)
{
HyperLink tA = (HyperLink)e.Row.FindControl("lnkTA");
tA.NavigateUrl = String.Format("/ExportStock?name={0}","ZZZZ");
tA.Text = Total0.StringEuro();
}
}
I've tried to ask on the e.Row.RowType == DataControlRowType.DataRow, if the value of the Hyperlink is 0, but if one value on the column is 0 it disables all hyperlinks on that column.
How can I remove only for the 0 cell?
Thanks.
CODE UPDATED

How to specify which control to use in the gridview rowupdate

I have a gridview and several template fields and several rowcommands. I would like to use the built in update row command but the problem I'm running into is making it so my application isn't functioning correctly.
Problem: In one of my edititem template fields I have both a Label control and a dropdown control. The reason for this is that I need to hide/show one or the other depending on the rowcommand is triggered. When I use the built in edit rowcommand I hide the dropdown and display the dropdownlist. So everything works there. However, when update rowcommand is triggered it is using the label value which is not visible and is bound to display the month rather than the full date that is needed. I use the drop down list to display the month to the user and the selected value is the full date. For some odd reason it wants to use the label value instead of the drop down list selected value even though I specify the update parameter in the code behind. If I remove the label from the commissionmonth column then everything works just fine except for the fact that on my other row commands the drop down list I would have to display a drop down list instead of the wanted label.
If any of you know how to specify the control to use in the update rowcommand or somehow dynamically change that column to read only on certain row commands I would greatly appreciate it!
Code Sample:
<asp:GridView ID="UnverifiedSalesGV" runat="server" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
DataSourceID="UnverifiedSalesSDS" ForeColor="Black" GridLines="Vertical"
Width="100%" ShowHeaderWhenEmpty="True" DataKeyNames="ID"
onrowupdating="UnverifiedSalesGV_RowUpdating"
onrowcommand="UnverifiedSalesGV_RowCommand"
onrowdatabound="UnverifiedSalesGV_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="EditBTN" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
<asp:Button ID="VerifyBTN" runat="server" Text="Verify" CommandName="VerifyRecord" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
<EditItemTemplate>
<asp:Button ID="UpdateBTN" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:Button ID="UpdateProductBTN" runat="server" Text="Verify" CommandName="UpdateProduct" Visible="false" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<asp:Button ID="CancelBTN" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CompanyName" HeaderText="Company"
SortExpression="CompanyName" ReadOnly="True" />
<asp:BoundField DataField="SalesRep" HeaderText="Sales Rep"
SortExpression="SalesRep" ReadOnly="True" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="AccountManager" HeaderText="Account Manager"
SortExpression="AccountManager" ReadOnly="True" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
SortExpression="ProductID" Visible="False" />
<asp:TemplateField HeaderText="Product" SortExpression="Product">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("Product") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="CurrentProductLBL" runat="server" Text='<%# Eval("Product") %>'></asp:Label>
<asp:DropDownList ID="RenewalProductDDL" runat="server"
DataSourceID="RenewalProductSDS" DataTextField="Product" DataValueField="ID" Visible="false">
</asp:DropDownList>
<asp:SqlDataSource ID="RenewalProductSDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Wizard_SwearsConnectionString1 %>"
SelectCommand="SELECT * FROM [Product] LEFT JOIN ProductToProductCategory AS Category ON Product.ID = Category.ProductID WHERE Category.ProductCategoryID = 5 AND Product.ID <> 38 ORDER BY [Product]"></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateFulfilled" DataFormatString="{0:M/d/yyyy}"
HeaderText="Date Fulfilled" SortExpression="DateFulfilled"
ReadOnly="True" />
<asp:TemplateField HeaderText="Gross Sales Amount"
SortExpression="GrossSalesAmount">
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("GrossSalesAmount", "{0:C}") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="GrossSalesLBL" runat="server"
Text='<%# Bind("GrossSalesAmount", "{0:C}") %>' Visible="false"></asp:Label>
<asp:TextBox ID="GrossSalesTXT" runat="server"
Text='<%# Bind("GrossSalesAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Net Sales Amount"
SortExpression="NetSalesAmount">
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("NetSalesAmount", "{0:C}") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="NetSalesLBL" runat="server" Text='<%# Bind("NetSalesAmount", "{0:C}") %>' Visible="false"></asp:Label>
<asp:TextBox ID="NetSalesTXT" runat="server" Text='<%# Bind("NetSalesAmount") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Commission Month"
SortExpression="CommissionMonth">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("CommissionMonth", "{0:MMMM}") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="CommissionMonthDDL" runat="server"
DataSourceID="SalesCommissionDDLSDS" DataTextField="Month"
DataValueField="CommissionMonth">
</asp:DropDownList>
<asp:Label ID="SalesCommissionLBL" runat="server"
Text='<%# Bind("CommissionMonth") %>' Visible="false" ></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Notes" SortExpression="Notes">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Notes") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="NotesLBL" runat="server" Text='<%# Bind("Notes") %>' Visible="false"></asp:Label>
<asp:TextBox ID="NotesTXT" runat="server" Text='<%# Bind("Notes") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Code behind:
protected void UnverifiedSalesGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.RowIndex)].FindControl("CommissionMonthDDL");
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.Update();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}
I was finally able to solve my problem with the following code:
//Verify and Update Record
protected void UnverifiedSalesGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
buttonCommand = e.CommandName;
if (buttonCommand != "Cancel" && buttonCommand != "Edit" && buttonCommand != "Sort")
{
//Get Gridview data key and row index
rowIndex = Convert.ToInt32(e.CommandArgument);
salesID = UnverifiedSalesGV.DataKeys[rowIndex].Value.ToString();
MessageLBL.Text = "";
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (buttonCommand == "VerifyRecord")
{
if (productID != "38")
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
//Get row index.
UnverifiedSalesGV.SetEditRow(rowIndex);
UnverifiedSalesGV.DataBind();
}
}
if (buttonCommand == "UpdateProduct")
{
DropDownList productValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("RenewalProductDDL");
if (productValue.SelectedIndex != 0)
{
try
{
UpdateSalesRecordSDS.UpdateCommand = "UPDATE Sales SET ProductID = #ProductID, Verified = #Verified WHERE ID = #ID";
UpdateSalesRecordSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UpdateSalesRecordSDS.UpdateParameters["ProductID"].DefaultValue = productValue.SelectedValue;
UpdateSalesRecordSDS.UpdateParameters["Verified"].DefaultValue = true.ToString();
UpdateSalesRecordSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
VerifiedSalesGV.DataBind();
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not verify sale. Message: " + ex.Message;
}
}
else
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Please select renewal type.";
}
}
if (buttonCommand == "UpdateRecord")
{
//Get date and user info
DateTime getDate = System.DateTime.Now;
MembershipUser user = Membership.GetUser();
string activeuser = user.UserName;
try
{
//Get dropdown and textbox values
string amid;
string commisionMonth;
string grossSalesAmount;
string netSalesAmount;
string notes;
DropDownList accountManagerID = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("AccountManagerDDL");
TextBox grossSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("GrossSalesTXT");
TextBox netSalesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NetSalesTXT");
TextBox notesValue = (TextBox)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("NotesTXT");
DropDownList commissionMonthValue = (DropDownList)UnverifiedSalesGV.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("CommissionMonthDDL");
amid = accountManagerID.SelectedValue;
grossSalesAmount = grossSalesValue.Text;
netSalesAmount = netSalesValue.Text;
commisionMonth = commissionMonthValue.SelectedValue;
notes = notesValue.Text;
UnverifiedSalesSDS.UpdateCommand = "UPDATE [Sales] SET [OriginalAMID] = #OriginalAMID, [GrossSalesAmount] = #GrossSalesAmount, [NetSalesAmount] = #NetSalesAmount, [Notes] = #Notes, [CommissionMonth] = #CommissionMonth, [DateLastModified] = #DateLastModified, [UserLastModified] = #UserLastModified WHERE [ID] = #ID";
UnverifiedSalesSDS.UpdateParameters["OriginalAMID"].DefaultValue = amid;
UnverifiedSalesSDS.UpdateParameters["GrossSalesAmount"].DefaultValue = grossSalesAmount;
UnverifiedSalesSDS.UpdateParameters["NetSalesAmount"].DefaultValue = netSalesAmount;
UnverifiedSalesSDS.UpdateParameters["CommissionMonth"].DefaultValue = commisionMonth;
UnverifiedSalesSDS.UpdateParameters["Notes"].DefaultValue = notes;
UnverifiedSalesSDS.UpdateParameters["DateLastModified"].DefaultValue = getDate.ToString();
UnverifiedSalesSDS.UpdateParameters["UserLastModified"].DefaultValue = activeuser;
UnverifiedSalesSDS.UpdateParameters["ID"].DefaultValue = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
UnverifiedSalesSDS.Update();
UnverifiedSalesGV.DataBind();
UnverifiedSalesGV.EditIndex = -1;
}
catch (Exception ex)
{
MessageLBL.ForeColor = Color.Red;
MessageLBL.Text = "Could not update record. Message: " + ex.Message;
}
}
}
}
//Hide and show fields
protected void UnverifiedSalesGV_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == rowIndex)
{
string state = e.Row.RowState.ToString();
if (state == "Alternate, Edit" || state == "Edit")
{
//Get record ID
string salesID = UnverifiedSalesGV.DataKeys[Convert.ToInt32(e.Row.DataItemIndex)].Value.ToString();
//Get productID
SalesData getSalesRecord = new SalesData();
getSalesRecord.GetRowValuesSalesID(salesID);
string productID = getSalesRecord.productID;
if (productID == "38")
{
//Items to Hide/Display
Button UpdateProductBTN = (Button)e.Row.FindControl("UpdateProductBTN");
Button UpdateBTN = (Button)e.Row.FindControl("UpdateBTN");
Label productLBL = (Label)e.Row.FindControl("CurrentProductLBL");
Label accountManagerLBL = (Label)e.Row.FindControl("AccountManagerLBL");
DropDownList productDDL = (DropDownList)e.Row.FindControl("RenewalProductDDL");
DropDownList accountManagerDDL = (DropDownList)e.Row.FindControl("AccountManagerDDL");
Label grossSalesLBL = (Label)e.Row.FindControl("GrossSalesLBL");
TextBox grossSalesTXT = (TextBox)e.Row.FindControl("GrossSalesTXT");
Label netSalesLBL = (Label)e.Row.FindControl("NetSalesLBL");
TextBox netSalesTXT = (TextBox)e.Row.FindControl("NetSalesTXT");
Label commissionMonthLBL = (Label)e.Row.FindControl("SalesCommissionLBL");
DropDownList commissionMonthDDL = (DropDownList)e.Row.FindControl("CommissionMonthDDL");
TextBox notesTXT = (TextBox)e.Row.FindControl("NotesTXT");
Label notesLBL = (Label)e.Row.FindControl("NotesLBL");
UpdateProductBTN.Visible = true;
UpdateBTN.Visible = false;
productLBL.Visible = false;
productDDL.Visible = true;
accountManagerLBL.Visible = true;
accountManagerDDL.Visible = false;
grossSalesLBL.Visible = true;
grossSalesTXT.Visible = false;
netSalesLBL.Visible = true;
netSalesTXT.Visible = false;
commissionMonthLBL.Visible = true;
commissionMonthDDL.Visible = false;
notesTXT.Visible = false;
notesLBL.Visible = true;
}
}
}
}

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