Add a new row in a gridview - asp.net

next code shows a table filled (a gridview) with 5 columns and several rows. It's running well
while (drCLientes.Read())
{
GridView gv = new GridView();
gv.ID = "myGridID";
cong.Open();
da = new OleDbDataAdapter(sql, cong);
ds = new DataSet("Clientes");
da.Fill(ds, "Clientes");
cong.Close();
gv.DataSource = ds.Tables["Clientes"];
gv.DataBind();
}
After this code, the result is this:
Table that I have
Now I need to add a new row, in the first position. The first column empty. The second and third one columns must be combined. The same with the 4th and 5th ones. Here is an image with the table that I need:
Table that I need
Regards

You need to use Repeater instead of GridView.
<asp:Repeater ID="repList" runat="server" OnItemCommand="repList_ItemCommand">
<HeaderTemplate>
<table cellpadding="3" cellspacing="0" border="1" style="border-collapse: collapse;"
width="100%">
<thead style="text-align: center;" class="Gridheader">
<tr>
<td rowspan="2">Sequence</td>
<td colspan="4">Student</td>
<td colspan="3">Lesson</td>
<td rowspan="2">Point</td>
</tr>
<tr>
<td>Name</td>
<td>Surname</td>
<td>Age</td>
<td>Class</td>
<td>Name</td>
<td>Teacher</td>
<td>Time</td>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td align="center">
<asp:Label ID="lblSequence" runat="server" >
</asp:Label>
</td>
<td>
<asp:Label ID="lblStudentName" runat="server" >
</td>
<td>
<asp:Label ID="lblStudentSurname" runat="server" >
</td>
<td>
<asp:Label ID="lblStudentAge" runat="server" >
</td>
<td>
<asp:Label ID="lblLessonClass" runat="server" >
</td>
<td>
<asp:Label ID="lblLessonName" runat="server" >
</td>
<td>
<asp:Label ID="lblLessonTeacher" runat="server" >
</td>
<td>
<asp:Label ID="lblLessonTime" runat="server" >
</td>
<td>
<asp:Label ID="lblLessonPoint" runat="server" >
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</FooterTemplate>
</asp:Repeater>
and Code Behind;
public void rptr_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Data.Common.DbDataRecord objRow = (System.Data.Common.DbDataRecord)e.Item.DataItem;
Label lblAnswer = e.Item.FindControl("lblSequence") as Label;
lblAnswer.Text = objRow["Sequence"].ToString();
Label lblStudentName = e.Item.FindControl("lblStudentName") as Label;
lblStudentName.Text = objRow["StudentName"].ToString();
...
..
.
}
}

Related

Conditional statement for Repeater Controll in ASP.NET

I am populating some data in a table with 6 columns using a repeater control in ASP.NET (VB) using the enclosed code.
I want a piece of code to achieve the following functionality by attaching an if/elseif/else condition to the repeater controll:
For the record with<%#Eval("SOLID")%> = "40103" then the data to be displayed in one cell, merging all 6 columns in to one (ideally using colspan = 6).
For the record having <%#Eval("SOLID")%> = "40105" then the data to be displayed in two cell, merging the second and third column.
For all the other records the data to be displayed in the actual format.
I have gone through various sites for a solution, but in vain. Please help me
<asp:Repeater ID="Repeater3" runat="server">
<headertemplate>
<tr style="height:25px;vertical-align:middle">
<th class ="dg_rpt_center" align="left" width = "10%" >
<asp:Label ID="Label7" runat="server" class ="lbl105" >SOLID</asp:Label></th>
<th class ="dg_rpt_center" align="left" width = "30%">
<asp:Label ID="Label10" runat="server" class ="lbl105" >SOL Name</asp:Label></th>
<th class ="dg_rpt_center" align="right" width = "10%">
<asp:Label ID="Label11" runat="server" class ="lbl105" >Target</asp:Label></th>
<th class ="dg_rpt_center" align="right" width = "10%">
<asp:Label ID="Label12" runat="server" class ="lbl105" >Achievement</asp:Label></th>
<th class ="dg_rpt_center" align="right" width = "10%">
<asp:Label ID="Label13" runat="server" class ="lbl105" >Margin</asp:Label></th>
<th class ="dg_rpt_center" align="right" width = "10%" >
<asp:Label ID="Label14" runat="server" class ="lbl105" >Growth</asp:Label></th>
</tr>
</headertemplate>
<ItemTemplate>
<tr>
<td align="left" width = "10%"><asp:LinkButton ID="lblsolid" runat="server" class ="lbl9N" Text='<%#Eval("SOLID")%>' OnClick='subDtClick' CommandArgument='<%#Eval("SLNO")%>'></asp:LinkButton></td>
<td align="left" width = "30%"><asp:Label ID="lblsolname" runat="server" class ="lbl9N" Text='<%#Eval("NAME")%>'></asp:Label></td>
<td align="right" width = "10%"><asp:Label ID="lbltgt" runat="server" class ="lbl9N" Text='<%#Eval("TGT")%>'></asp:Label></td>
<td align="right" width = "10%"><asp:Label ID="lblach" runat="server" class ="lbl9N" Text='<%#Eval("ACH")%>'></asp:Label></td>
<td align="right" width = "10%"><asp:Label ID="lblmrgn" runat="server" class ="lbl9N" Text='<%#Eval("MGR")%>'></asp:Label></td>
<td align="right" width = "10%"><asp:Label ID="lblgr" runat="server" class ="lbl9N" Text='<%#Eval("GRW")%>'></asp:Label></td>
</tr>
</ItemTemplate>
</asp:Repeater>
To achieve this you can write your logic in the ItemDataBound event of the Repeater control. You will need to get references of your table cells and labels, then set your colspan, merge your label values, and hide any extra cells.
ASPX page
<asp:Repeater ID="Repeater3" runat="server" OnItemDataBound="Repeater3_ItemDataBound">
<HeaderTemplate>
<tr style="height: 25px; vertical-align: middle">
<th class="dg_rpt_center" align="left" width="10%">
<asp:Label ID="Label7" runat="server" class="lbl105">SOLID</asp:Label></th>
<th class="dg_rpt_center" align="left" width="30%">
<asp:Label ID="Label10" runat="server" class="lbl105">SOL Name</asp:Label></th>
<th class="dg_rpt_center" align="right" width="10%">
<asp:Label ID="Label11" runat="server" class="lbl105">Target</asp:Label></th>
<th class="dg_rpt_center" align="right" width="10%">
<asp:Label ID="Label12" runat="server" class="lbl105">Achievement</asp:Label></th>
<th class="dg_rpt_center" align="right" width="10%">
<asp:Label ID="Label13" runat="server" class="lbl105">Margin</asp:Label></th>
<th class="dg_rpt_center" align="right" width="10%">
<asp:Label ID="Label14" runat="server" class="lbl105">Growth</asp:Label></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td id="tdSOLID" runat="server" align="left" width="10%">
<asp:LinkButton ID="lblsolid" runat="server" class="lbl9N" Text='<%#Eval("SOLID")%>' CommandArgument='<%#Eval("SLNO")%>'></asp:LinkButton></td>
<td id="tdNAME" runat="server" align="left" width="30%">
<asp:Label ID="lblsolname" runat="server" class="lbl9N" Text='<%#Eval("NAME")%>'></asp:Label></td>
<td id="tdTGT" runat="server" align="right" width="10%">
<asp:Label ID="lbltgt" runat="server" class="lbl9N" Text='<%#Eval("TGT")%>'></asp:Label></td>
<td id="tdACH" runat="server" align="right" width="10%">
<asp:Label ID="lblach" runat="server" class="lbl9N" Text='<%#Eval("ACH")%>'></asp:Label></td>
<td id="tdMGR" runat="server" align="right" width="10%">
<asp:Label ID="lblmrgn" runat="server" class="lbl9N" Text='<%#Eval("MGR")%>'></asp:Label></td>
<td id="tdGRW" runat="server" align="right" width="10%">
<asp:Label ID="lblgr" runat="server" class="lbl9N" Text='<%#Eval("GRW")%>'></asp:Label></td>
</tr>
</ItemTemplate>
</asp:Repeater>
Code Behind
public void Repeater3_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
var lblsolid = (LinkButton)e.Item.FindControl("lblsolid");
if (lblsolid.CommandArgument == "40103" || lblsolid.CommandArgument == "40105") {
//Labels
var lblsolname = (Label) e.Item.FindControl("lblsolname");
var lbltgt = (Label) e.Item.FindControl("lbltgt");
var lblach = (Label) e.Item.FindControl("lblach");
var lblmrgn = (Label) e.Item.FindControl("lblmrgn");
var lblgr = (Label) e.Item.FindControl("lblgr");
//Table Cells
var tdSOLID = (HtmlTableCell)e.Item.FindControl("tdSOLID");
var tdNAME = (HtmlTableCell)e.Item.FindControl("tdNAME");
var tdTGT = (HtmlTableCell)e.Item.FindControl("tdTGT");
var tdACH = (HtmlTableCell)e.Item.FindControl("tdACH");
var tdMGR = (HtmlTableCell)e.Item.FindControl("tdMGR");
var tdGRW = (HtmlTableCell)e.Item.FindControl("tdGRW");
if (lblsolid.CommandArgument == "40103") {
//merge all label values into a single string
var mergedCellValues = string.Format("{0} {1} {2} {3} {4}", lblsolname.Text, lbltgt.Text, lblach.Text, lblmrgn.Text, lblgr.Text);
//set the text value of the first table cell and span it 6 columns
tdSOLID.InnerText = mergedCellValues;
tdSOLID.Attributes.Add("colspan", "6");
//remove extra cells
tdNAME.Visible = false;
tdTGT.Visible = false;
tdACH.Visible = false;
tdMGR.Visible = false;
tdGRW.Visible = false;
} else if (lblsolid.CommandArgument == "40105") {
//same concept as above, but with different colspan and cell hiding
}
}
}
}

asp.net- Highlight cell in listview

I have this piece of code which works fine and highlights the label. However, I want it to highlight the entire cell not just the label.
Any help would be appreciated!
protected void HighLight_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label TotalTimeLabel = (Label)e.Item.FindControl("TotalTime");
if (TotalTimeLabel != null)
{
Decimal Total;
if (Decimal.TryParse(TotalTimeLabel.Text, out Total) == true)
{
if (Total > (Decimal)1.5)
{
TotalTimeLabel.BackColor = System.Drawing.Color.Red;
TotalTimeLabel.ForeColor = System.Drawing.Color.Black;
}
}
}
}
}
The code for the table is below
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" OnItemDataBound="HighLight_ItemDataBound" >
<LayoutTemplate>
<table cellpadding="1" class="TableCSS" runat="server" id="tblProducts">
<tr runat="server" style="background-color:lightgrey">
<th runat="server">enNotificationNoNI</th>
<th runat="server">TotalTime</th>
<th runat="server">TPTIMEIN</th>
<th runat="server">Status</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server" class="TableData">
<td>
<asp:Label ID="enNotificationNoNI" runat="Server" Text='<%#Eval("enNotificationNoNI") %>' />
</td>
<td>
<asp:Label ID="TotalTime" runat="Server" Text='<%#Eval("TotalTime") %>' />
</td>
<td>
<asp:Label ID="TPTIMEIN" runat="Server" Text='<%#Eval("TPTIMEIN") %>' />
</td>
<td>
<asp:Label ID="Status" runat="Server" Text='<%#Eval("Status") %>' />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Try this code
For entire row
Control ctrl = TotalTimeLabel.Parent.Parent;
HtmlTableRow tblrw = (HtmlTableRow)ctrl;
tblrw.BgColor = System.Drawing.Color.Red.Name;
For one cell
Control ctrl = TotalTimeLabel.Parent;
HtmlTableCell tblcl = (HtmlTableCell)ctrl;
tblcl.BgColor = System.Drawing.Color.Red.Name;
let me know whether this works :)

drop down list Selected index changed event not working

On my form,I am having one drop down list.I have filled drop down list on page load event.Even i have check if not is post back.My drop down list's auto post back property is true.But still the event is not firing.I have to show some value in text box on selected index changed of drop down list.
my design code is as below:
enter code here
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<table class="tblContentcss">
<tr>
<td class="tdContent1css">
<asp:Label runat="server" ID="lblUserRole" Text="Role"></asp:Label>
</td>
<td class="tdContent2css">
:
</td>
<td class="tdContent3css">
<asp:TextBox runat="server" ID="txtUserRole" Text="User" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<tr>
<td class="tdContent1css">
<asp:Label runat="server" ID="lblUserID" Text="User ID"></asp:Label>
</td>
<td class="tdContent2css">
:
</td>
<td class="tdContent3css">
<asp:DropDownList ID="ddlUserID" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlUserID_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="tdContent1css">
<asp:Label runat="server" ID="lblUserName" Text="User Name"></asp:Label>
</td>
<td class="tdContent2css">
:
</td>
<td class="tdContent3css">
<asp:TextBox runat="server" ID="txtUserName" AutoPostBack="true"></asp:TextBox>
</td>
</tr>
<tr>
<td class="tdContent1css">
<asp:Label runat="server" ID="lblUserPassword" Text="Password"></asp:Label>
</td>
<td class="tdContent2css">
:
</td>
<td class="tdContent3css">
<asp:TextBox runat="server" ID="txtPassword" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td class="tdContent1css">
<asp:Label runat="server" ID="Label1" Text="Password"></asp:Label>
</td>
<td class="tdContent2css">
:
</td>
<td class="tdContent3css">
<asp:Button runat="server" ID="btnSave" Text="Save" OnClick="btnSave_Click" />
</td>
</tr>
</table>
</div>
</asp:Content>
and in.cs on page_load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillUserID();
}
}
protected void ddlUserID_SelectedIndexChanged(object sender, EventArgs e)
{
fillUserID();
SqlConnection con = dal.GetConnection();
dsUserName = new DataSet();
query = "SELECT CUSTID,(FNAME+' '+MNAME+' '+LNAME) AS USERNAME FROM CUSTOMER where CUSTID=" + Convert.ToInt32(ddlUserID.SelectedValue) + "";
dsUserName = dal.ReturnDataset(query, con);
if (dsUserName.Tables.Count > 0 && dsUserName.Tables[0].Rows.Count > 0)
{
txtUserName.Text = dsUserName.Tables[0].Rows[0]["USERNAME"].ToString();
}
}
what is the problem,i am not getting.
Suggest me any solution
When the autopostback is set True, after the page is rendered, a javascript is added on the onchange event of the dropdown (SELECT in HTML) to trigger the postback,
View the source after the page is rendered and check whether the javascript is getting added to the onchange event of the dropdown.
If you are adding some javascript on the onchange event of the dropdown in the code-behind, that might also stop the page to postback.
I get that from this link: https://www.codeproject.com/Questions/138183/Drop-down-selected-index-change-event-not-working

How to get values from templatefields in Gridview

I have a gridview with template fields.
I want when I press the imagebutton to get the values of the Labels inside the ItemTemplate.
<asp:GridView ID="GridView1" ShowHeader="False"
GridLines="None" AutoGenerateColumns="False"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table style="border: 0px solid">
<tr>
<td style="width: 220px">
<asp:Image ID="imgEmployee" BorderStyle="Solid" Height="182px" Width="235px"
ImageUrl='<%# Eval("Photo")%>'
runat="server" />
</td>
<td style="width: 600px">
<table>
<tr>
<td>
<b>ID:</b>
</td>
<td>
<asp:Label ID="lblId"
runat="server"
Text='<%#Eval("id")%>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Item:</b>
</td>
<td>
<asp:Label ID="lblItem"
runat="server"
Text='<%#Eval("Item")%>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Price:</b>
</td>
<td>
<asp:Label ID="lblPrice"
runat="server"
Text='<%#Eval("Price")%>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<b>Notes:</b>
</td>
<td>
<asp:Label ID="lblNotes"
runat="server"
Text='<%#Eval("Notes")%>'>
</asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server" Text ="1" ></asp:TextBox>
</td>
<td>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/buy.png" CommandName="AddToBasket" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In GridView1_RowCommand I have the following code
If e.CommandName = "AddToBasket" Then
Here i want to take the values of the labels
You need to attach OnRowCommand event method to the GridView first:
<asp:GridView ID="GridView1" ShowHeader="False"
GridLines="None" AutoGenerateColumns="False"
OnRowCommand ="GridView1_RowCommand"
runat="server">
You can get the GridViewRow from commandsource's NamingContainer and use FindControl method to find the Labels like below:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToBasket")
{
int id = 0;
string item = string.Empty; ;
decimal price = 0.00m;
string notes = string.Empty;
var gvRow = ((ImageButton)e.CommandSource).NamingContainer as GridViewRow;
var lblId = gvRow.FindControl("lblId") as Label;
var lblItem = gvRow.FindControl("lblId") as Label;
var lblPrice = gvRow.FindControl("lblId") as Label;
var lblNotes = gvRow.FindControl("lblId") as Label;
if (lblId != null && lblItem != null && lblPrice != null && lblNotes != null)
{
int.TryParse(lblId.Text, out id);
item = lblItem.Text;
decimal.TryParse(lblPrice.Text, out price);
notes = lblNotes.Text;
}
}
}

How do I transpose ASP.NET ListView grid layout?

I'm new to ASP.NET and am trying to create a repeating detailsview type format. By this I mean that the first column is a header type column and subsequent columns are the data records.
Records Rec1 Rec 2 Rec3
Header A Fld A Fld A Fld A
Header B Fld B Fld B Fld B
I've tried a couple iterations of the following based on this example:
<asp:ListView ID="ListView2" runat="server" DataKeyNames="FldA" DataSourceID="EntityRecordSource" GroupItemCount="3">
<LayoutTemplate>
<table id="Table1" runat="server">
<tr id="Tr21" runat="server">
<td id="Td1" runat="server">
<table id="Table2" runat="server" border="0" style="">
<tr id="Tr1" runat="server" style="">
<th id="Th1" runat="server"></th>
</tr>
<tr id="Tr2" runat="server" style="">
<th id="Th2" runat="server">FldA</th>
</tr>
<tr id="Tr3" runat="server" style="">
<th id="Th3" runat="server">FldB</th>
</tr>
<tr id="Tr4" runat="server" style="">
<th id="Th4" runat="server">FldC</th>
</tr>
</table>
</td>
<td>
<table>
<asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
</table>
</td>
</tr>
<tr id="Tr22" runat="server">
<td id="Td2" runat="server" style="">
<asp:DataPager ID="DataPager1" runat="server">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
<GroupTemplate >
<tr id="Tr1" runat="server" style="">
<asp:PlaceHolder runat="server" ID="itemPlaceHolder1"></asp:PlaceHolder>
</tr>
<tr id="Tr2" runat="server" style="">
<asp:PlaceHolder runat="server" ID="itemPlaceHolder2"></asp:PlaceHolder>
</tr>
<tr id="Tr3" runat="server" style="">
<asp:PlaceHolder runat="server" ID="itemPlaceHolder3"></asp:PlaceHolder>
</tr>
</GroupTemplate>
<ItemTemplate>
<td>
<asp:Label ID="FldALabel" runat="server" Text='<%# Eval("FldA") %>' />
</td>
<td>
<asp:Label ID="FldBLabel" runat="server" Text='<%# Eval("FldB") %>' />
</td>
<td>
<asp:Label ID="FldCLabel" runat="server" Text='<%# Eval("FldC") %>' />
</td>
</ItemTemplate>
</asp:ListView>
However this results in an error stating :
System.Web.UI.HtmlControls.HtmlTableCellCollection must have items of type 'System.Web.UI.HtmlControls.HtmlTableCell'. 'asp:PlaceHolder' is of type 'System.Web.UI.WebControls.PlaceHolder'.
Thanks in advance for your help.
I wanted basically the same thing, here is the method I wrote to accomplish this:
internal static void TransposeListview(ListView lv)
{
if (lv.Items.Count == 0)
throw new ArgumentException("ListView has no items, so values cannot be transposed.", "lv");
// first, convert the column headers into a first row
var columnHeaderValues = (from ColumnHeader ch in lv.Columns select ch.Text).ToArray();
lv.Items.Insert(0, new ListViewItem(columnHeaderValues, 0));
var cols = lv.Columns.Count;
var rows = lv.Items.Count;
// create a list of ListViewSubItem arrays, to hold the target values
var lvsiArrayList = new List<ListViewItem.ListViewSubItem[]>();
for (var i = 0; i <= cols - 1; i++)
{
var lvsiArray = new ListViewItem.ListViewSubItem[rows];
for (var j = 0; j <= rows - 1; j++)
lvsiArray[j] = lv.Items[j].SubItems[i];
lvsiArrayList.Add(lvsiArray);
}
// now clear the whole ListView, and create the items and subitems using flipped row/column indexes
lv.Clear();
foreach (var lvsiArray in lvsiArrayList)
lv.Items.Add(new ListViewItem(lvsiArray, 0));
// last, convert the first row into column headers
columnHeaderValues = (from ListViewItem.ListViewSubItem lvsi in lv.Items[0].SubItems select lvsi.Text).ToArray();
for (var j = 0; j <= rows - 1; j++)
lv.Columns.Add(columnHeaderValues[j]);
lv.Items.RemoveAt(0);
}

Resources