Calling Data From GridView - asp.net

I have a GridView with a bunch of DynamicFields like so;
<asp:GridView ID="GridView1" runat="server" DataSourceID="GridDataSource">
<Columns>
<asp:DynamicField HeaderText="Date Submitted" DataField="DATE_CREATED" />
<asp:DynamicField HeaderText="Assigned To" DataField="ASSIGNED_TO" />
<asp:DynamicField HeaderText="Active Account" DataField="Active_Account" />
<asp:DynamicField HeaderText="Client ID" DataField="CLIENT_ID" />
<asp:DynamicField HeaderText="Client Type" DataField="CLIENT_Type" />
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="GridDataSource" OnSelected="TotalRows" runat="server"
EnableDelete="true">
<WhereParameters>
<asp:DynamicControlParameter ControlID="FilterRepeater" />
</WhereParameters>
</asp:EntityDataSource>
Now it displays fine, the right data comes to screen but when I try to access that data using a row number I'm always finding blank cells. For example I tried the following to check every cell but to no avail;
Dim x As Integer = 0
Dim y As Integer = 0
While x < GridView1.Rows.Count
While y < GridView1.Rows(x).Cells.Count
If Not (GridView1.Rows(x).Cells(y).Text = "") Then
MsgBox(String.Format("{0},{1},{2}", x.ToString, y.ToString,
GridView1.Rows(x).Cells(y).Text))
End If
y = y + 1
End While
x = x + 1
y = 0
End While
No message box displayed so all the cells are empty strings. But I can clearly see they're populated on screen! What am I doing wrong?
UPDATE
After Pilgerstorfer Franz suggestion that I look for Textbox elements I used the following code which basically looks at all the cells in the table and try's to pull data out of them and if it's not blank then display a msgbox (also informs me of any new controls I haven't accounted for);
If GridView1.Rows(0).RowType = DataControlRowType.DataRow Then
For r = 0 To GridView1.Rows.Count - 1
For c = 0 To (GridView1.Rows(r).Cells.Count - 1)
Dim cell = GridView1.Rows(r).Cells(c)
For b = 0 To cell.Controls.Count - 1
If (cell.Controls(b).GetType() Is GetType(TextBox)) Then
Dim td = CType(cell.Controls(b), TextBox)
Text = td.Text.Trim
ElseIf (cell.Controls(b).GetType() Is GetType(LiteralControl)) Then
Dim td = CType(cell.Controls(b), LiteralControl)
Text = td.Text.Trim
ElseIf (cell.Controls(b).GetType() Is GetType(DynamicControl)) Then
Dim td = CType(cell.Controls(b), DynamicControl)
Text = td.Table.Columns.Item(c).DisplayName()
Else
MsgBox(String.Format("New Control of type: {0}", cell.Controls(b).GetType().FullName))
End If
If Not Text = "" Then
MsgBox(String.Format("{0},{1},{2}", c.ToString, b.ToString, Text))
End If
Next
Next
Next
End If
Unfortunately most cells just contained DynamicControl and since I was putting the DisplayName into Text I was just getting the column header every time. So how do I get the text value property out of a DynamicControl?
Additional Info
I'm further confused by this problem because since this is a project that I'm updating there is initial code two lines of which are;
Dim UserID = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value)
Dim clientType As String = GridView1.DataKeys(e.RowIndex).Item(1).ToString
These successfully bring back UserID and ClientType. Now I don't really understand DataKeys but I tried using;
Dim clientType As String = GridView1.DataKeys(e.RowIndex).Item(Num).ToString
where Num increases by one every time expecting it to bring back the rest of the row data, but I simply got an index was out of range error.
ANOTHER UPDATE!!
Here is another bit of the ASPX page but I'n not entirely certain what it does. Pilgerstorfer Franz created some code to look for the textboxes created by the dynamicControl. Now I'm wondering if this code here causes other types of controls to be used rather than Textboxes. Thoughts?
<asp:FilterRepeater ID="FilterRepeater" runat="server" Visible="false">
<ItemTemplate>
<h2><asp:Label ID="lblDisplay" runat="server" Text='<%#
Eval("DisplayName") %>' AssociatedControlID="DynamicFilter$DropDownList1" /></h2>
<asp:DynamicFilter runat="server" ID="DynamicFilter"
OnSelectedIndexChanged="OnFilterSelectedIndexChanged" />
</ItemTemplate>
<FooterTemplate><br /><br /></FooterTemplate>
</asp:FilterRepeater>

According to my assumptions (see comments) I did a small demo...
<asp:DynamicDataManager ID="DynamicDataManager1" runat="server">
<DataControls>
<asp:DataControlReference ControlID="GridView1" />
</DataControls>
</asp:DynamicDataManager>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ContactID" DataSourceID="EntityDataSource1" AllowPaging="true"
OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:DynamicField DataField="ContactID" ReadOnly="true" HeaderText="ContactID" />
<asp:DynamicField DataField="Title" HeaderText="Title" />
<asp:DynamicField DataField="FirstName" HeaderText="FirstName" />
<asp:DynamicField DataField="LastName" HeaderText="LastName" />
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
<asp:EntityDataSource ID="EntityDataSource1" runat="server" ConnectionString="name=dbTestIT34_EFEntities"
DefaultContainerName="dbTestIT34_EFEntities" EnableFlattening="False" EnableUpdate="True"
EntitySetName="Contacts" EntityTypeFilter="Contact">
</asp:EntityDataSource>
And according to my data storage I did handle the rowUpdating event. Unfortunatelly accessing any control within a dynamic control is not easy. So I did a very quick and dirty hack...
protected void Page_Init(object sender, EventArgs e)
{
GridView1.EnableDynamicData(typeof(Contact));
EntityDataSource1.ContextType = typeof(dbTestIT34_EFEntities);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int row = 0;
int firstNameColumn = 2;
while (row < GridView1.Rows.Count)
{
// sorry, a little bit confusing ...
// as dynamic control generates other controls dynamically,
// this was the very first thing that worked for me!
TextBox t = GridView1.Rows[row].Cells[firstNameColumn].Controls[0].Controls[0].Controls[0] as TextBox;
if (t != null)
Debug.WriteLine(t.Text);
row++;
}
}
Hope that helps!

Iterating through the controls never worked for me so in the end I gave up and just queried the DB again... Eh it works.

Related

styling certain rows in my gridview asp.net

so I have a gridview which is displaying a db table I have.
I dont create the table manually obviously as this is what <%#Eval("text")%>' and Bind() do.
I created a unique table with my sql query to add two rows of sum in the bottom of the table, ( 2 last records), my question is:
is there a way in which I can access those rows to style them?
I think its not possible but still Im asking maybe Ill find out that theres a way.
thanks
Yes, the need to style a individual cell (auto generated columns, or bound columns), or even style the whole row.
Let's do all 3
First up, style a "cell" (these are in the cells collection, and autogenerated columns, and NON templated columns).
So, say this simple grid
<asp:GridView ID="GridView1" runat="server" Width="40%"
AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table table-hover">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescript" runat="server"
Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkActive" runat="server"
Checked='<%# Eval("Active") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
(note how I included BOTH templated columns which have plain jane asp.net controls like label, textbox etc., or the built in GV columns (data bound ones, or auto generated)
Code to load the GV is this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadData()
End If
End Sub
Sub LoadData()
Dim strSQL = "SELECT * FROM tblHotelsA ORDER BY HotelName"
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand(strSQL, conn)
conn.Open()
Dim rst As New DataTable
rst.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rst
GridView1.DataBind()
End Using
End Using
End Sub
And we now have this:
Ok, so let's do example 1 - lets color the "city" Colum in above. Note how "city" is a "bound field".
So, auto generated, or bound fields = cells collection.
So, for things like conditional formatting, even combine some columns, change color, hide show images, or whatever?
you use the GV row databound event. (and this applies well to listview, repeaters, etc.)
So, lets say for city = Edmonton, we want a light blue cell, and for city = "Edmonton", we want some light green.
So, we use the row bound event.
This code:
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Select Case e.Row.Cells(3).Text
Case "Edmonton"
e.Row.Cells(3).BackColor = System.Drawing.Color.SkyBlue
Case "Banff"
e.Row.Cells(3).BackColor = System.Drawing.Color.LightGreen
End Select
End If
End Sub
And we now have this:
However, the above for "templated" colums works a bit different.
Lets say we want to highligh the description when check box = true (checked).
In that case, we can't (don't) use the cells colleciton, but for templated controls, we use find control.
Like this:
Dim cActive As CheckBox = e.Row.FindControl("chkActive")
If cActive.Checked Then
Dim lblDes As Label = e.Row.FindControl("lblDescript")
lblDes.Font.Italic = True
e.Row.Cells(4).BackColor = System.Drawing.Color.LightGray
End If
NOTE how we EVEN set the font to italic in the label control.
And now we see this:
NOTE VERY close how we use findcontrol to get those templated controls.
Last but not least - bonus:
let's highlight the whole row for active, and NOT EVEN have the check box column in the GV (but it is in the database source).
So, say this markup for the columns:
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescript" runat="server"
Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
So, "active" check box is NOT EVEN displayed in the GV, (but, it is in the data source that feeds the gv).
So, we can do this:
Protected Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gData As DataRowView = e.Row.DataItem ' Grid data - NOT the GV row!!!!!!
If gData.Item("Active") = True Then
e.Row.Style.Add("Background-color", "LightGray") ' highlight whole row.
End If
End If
End Sub
And we now get this:
Just keep in mind that the "dataitem" (the full database row) is ONLY avaiable during the row data bind, and it WILL/DOES go out of scope once data binding is complete.
so basically using pretty much similar logics as albert's reply, I ended up catching two last rows manually and changing their colors.
protected void grdReports_PreRender(object sender, EventArgs e)
{
//finding 2 last rows, changing backcolor to the sum specified color '#5D7B9D' and the forecolor to white
//first table ( annual )
GridViewRow lastRow = grdReports.Rows[grdReports.Rows.Count - 1];
lastRow.BackColor = System.Drawing.Color.FromName("#5D7B9D");
lastRow.ForeColor = Color.White;
GridViewRow secondToLastRow = grdReports.Rows[grdReports.Rows.Count - 2];
secondToLastRow.BackColor = System.Drawing.Color.FromName("#5D7B9D");
secondToLastRow.ForeColor = Color.White;
//second table ( requested )
GridViewRow lastRowSecond = grdReports2.Rows[grdReports2.Rows.Count - 1];
lastRowSecond.BackColor = System.Drawing.Color.FromName("#5D7B9D");
lastRowSecond.ForeColor = Color.White;
GridViewRow secondToLastRowSecond = grdReports2.Rows[grdReports2.Rows.Count - 2];
secondToLastRowSecond.BackColor = System.Drawing.Color.FromName("#5D7B9D");
secondToLastRowSecond.ForeColor = Color.White;
}

How to use checkbox check change without refreshing page in ASP.NET

I have two checkboxes in a gridview. The scenario is this: only one of these checkboxes can be chosen or none of them.
My problem is that when my gridview got too big, every time I check or uncheck each row the page refresh that is because of I set auto post back = true! What should I do to avoid this refreshing and the scenario works except UpdatePanel!
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" BackColor="White">
<Columns>
<asp:TemplateField HeaderText="morakhasi" ItemStyle-Width="80">
<ItemTemplate><asp:CheckBox ID="chkboxMorakhasi" OnCheckedChanged="chkboxMorakhasi_CheckedChanged" runat="server" AutoPostBack="true"/>
</ItemTemplate>
<HeaderStyle Font-Size="16px" Width="80px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="taiid" ItemStyle-Width="80">
<ItemTemplate><asp:CheckBox ID="chkboxTaiid" OnCheckedChanged="chkboxTaiid_CheckedChanged" runat="server" Checked="True" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</gridview>
Code behind:
protected void chkboxTaiid_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)GridView2.Rows[index].FindControl("chkboxTaiid");
CheckBox cb2 = (CheckBox)GridView2.Rows[index].FindControl("chkboxMorakhasi");
cb2.Checked = Convert.ToBoolean(0);
}
}
protected void chkboxMorakhasi_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow gr in GridView2.Rows)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox cb1 = (CheckBox)GridView2.Rows[index].FindControl("chkboxTaiid");
CheckBox cb2 = (CheckBox)GridView2.Rows[index].FindControl("chkboxMorakhasi");
cb1.Checked = Convert.ToBoolean(0);
}
}
You should use UpdatePanel control to do this
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:CheckBox
OnCheckedChanged="chkCompany_OnCheckedChanged"
AutoPostBack="True" CssClass="chkCompany"
ClientIDMode="Static" ID="chkCompany" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Well, first up, when you say the grid is large? Well, how large? 20 rows or 2000 rows?
When Google, or even Microsoft asks interview questions? A good number of these questions are of a how high, how far, how big type of questions. And the reason for that is simple:
They want to determine if you have a mind can is able to evaluate scope and scale of problems that you have to solve. (so, they might ask how would you move Mount Fuji?)
anyway:
I can't image the grid has what, 30 rows on a page? (why so many and why so large??).
I mean, if you have more, then we need to know how many more?
However, lets get the first problem solved. (the check box issue), and then we can try and deal with the re-plot/refresh issue.
Ok, so say we have this grid markup - grid + 2 check boxes
<asp:GridView ID="GVHotels" runat="server" class="table" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Choice 1" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server"
OnCheckedChanged="chk1_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Choice 2" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chk2" runat="server"
OnCheckedChanged="chk2_CheckedChanged" AutoPostBack="true"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code to load the grid is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST3))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we have this:
And our two check box changed events are this:
protected void chk1_CheckedChanged(object sender, EventArgs e)
{
CheckBox ck = (CheckBox)sender;
GridViewRow gRow = (GridViewRow)ck.Parent.Parent;
if (ck.Checked)
// uncheck the other box
((CheckBox)gRow.FindControl("chk2")).Checked = false;
}
protected void chk2_CheckedChanged(object sender, EventArgs e)
{
CheckBox ck = (CheckBox)sender;
GridViewRow gRow = (GridViewRow)ck.Parent.Parent;
if (ck.Checked)
// uncheck the other box
((CheckBox)gRow.FindControl("chk1")).Checked = false;
}
Ok, so we are done.
the next issue is performance? A grid of say 20-40 rows on the form should work ok.
I think just drop a update panel around the grid, and you done.
So, we drop in script manager, and then this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
-- above grid goes here!!!
</ContentTemplate>
</asp:UpdatePanel>
Now, I just tested the above with 50 rows on the screen. I can't see or feel, or notice ANY replot delay, and in fact the check box reacts as fast as my mouse click. In fact the check box status changes quite much as fast as the mouse click, and in fact quite much at the same time I hear the click.
So, above is the layout for the code you require here. If there is some "slow" ness, or delay, or your data set is larger, then perhaps some kind of data pager should be introduced. On the other hand, you not shared, or noted how many rows this grid is displaying on the screen. And without that information, we shooting in the dark here as to what possible solutions(s) exist (or that what you have is a very bad idea).

Extract a BoundField to a Label

I have a DetailsView which works fine using a data access layer and a query string. However, I'd like to extract one of the fields and use it as the text in a label to go above the DetailsView as a title to that page.
Is this possible? And if so, how?
This is an abstract of the DetailsView:
<Fields>
<asp:BoundField DataField="bandname" HeaderText="Band" />
<asp:BoundField DataField="contactname" HeaderText="Contact" />
<asp:BoundField DataField="county" HeaderText="County" />
</Fields>
and the code behind:
if (Request.QueryString.Count != 0)
{
int id = int.Parse(Request.QueryString["bandid"]);
dtvBand.Visible = true;
List<Band> bandDetails = new List<Band> { BandDAL.AnonGetAllBandDetails(id) };
dtvBand.DataSource = bandDetails;
dtvBand.DataBind();
}
What I'd like to do is take the data in the first BoundField row and make it the text of a label. Pseudocode:
Label1.Text = (<asp:BoundField DataField="band")
I would not try to find the text on the DetailsView but in it's DataSource. You could use the DataBound event which is triggered after the DetailsView was databound, so it's ensured that the DataItem exists.
It depends on the Datasource of your DetailsView. Often it is a DataRowView. You have to cast it, then you can access it's column:
protected void DetailsView1_DataBound(Object sender, EventArgs e)
{
DetailsView dv = (DetailsView)sender;
string yourText = (string)((DataRowView)dv.DataItem)["ColumnName"];
Label1.Text = yourText;
}
If it's not a DataRowView use the debugger to see what dv.DataItem actually is.
I managed to achieve what I wanted using:
string titletext = dtvBand.Rows[0].Cells[1].Text.ToString();
dtvBand.Rows[0].Visible = false;
lblBand.Text = titletext;
It takes the first row of the DetailsView, puts it above the rest in a Label so it can be formatted as a header, then hides the first row of the DetailsView.
How about using a TemplateField as what Tim mentioned:
<Fields>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Band") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>

Gridview not sorting

I've come across this strange error and it's been bugging me for hours now.
I've got some LinkButtons on my screen and depending on which button the user chooses a label's text is set, a GridView is displayed and the Datasource of this GridView is assigned based on the text of the label.
This all works fine and dandy. However the problem arises when I want to sort this GridView.
At the moment, nothing happens. When I attempt to sort a column the page just refreshes and I'm left with the same unsorted mess in my GridView.
I've put my application into debug mode with breakpoints along the way and noticed that when I get to this step (the full code can be seen at the bottom of this post) :
senderGridView.SortExpression = button.CommandArgument
the senderGridView.SortExpression is "" so for some reason it's not passing the sort expression.
Hopefully somebody can enlighten me as to why my grid isn't sorting as I'm sure it's just a stupid mistake somewhere but any help would be appreciated, thanks.
Code that you may require...
My sub that sets the sort images when a row is created can be seen below:
Protected Sub GridViewSortImages(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim senderGridView As GridView = CType(sender, GridView)
'Loop through each cell in header row
For Each cell As TableCell In e.Row.Cells
If cell.HasControls Then
Dim button As LinkButton = TryCast((cell.Controls(0)), LinkButton)
Dim gv As New HtmlGenericControl("div")
Dim lnkName As New Label()
'Test cell to see if a link button exists (i.e. Allow Sorting = True)
If Not (button Is Nothing) Then
'Create new label and image and set to standard unsorted view
lnkName.Text = button.Text
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "images/sort-1x1.png"
image.ToolTip = "Sort"
image.AlternateText = "Sort"
'Test to see if grid is already sorted, and apply relevant image & tooltip
If senderGridView.SortExpression = button.CommandArgument Then
If senderGridView.SortDirection = SortDirection.Ascending Then
image.ImageUrl = "images/sort-asc.png"
image.ToolTip = "Sort Descending"
image.AlternateText = "Sort Descending"
Else
image.ImageUrl = "images/sort-desc.png"
image.ToolTip = "Sort Ascending"
image.AlternateText = "Sort Ascending"
End If
End If
'Add label and image to new div
gv.Controls.Add(lnkName)
gv.Controls.Add(image)
'Replace original column header with new div
button.Controls.Add(gv)
End If
End If
Next
End Sub
My RowCreated sub for the GridView...
Protected Sub grvHomeRisk_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles grvHomeRisk.RowCreated
If Not (e.Row Is Nothing) AndAlso e.Row.RowType = DataControlRowType.Header Then
GridViewSortImages(sender, e) 'Call sort code
End If
End Sub
My Sorting sub...
Protected Sub grvHomeRisk_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grvHomeRisk.Sorting
Select Case lblBreachHeaderb.Text
Case "Current Risks"
grvHomeRisk.DataSource = SQLDS_ListCurrentRisk
Case "All Risks Overdue"
grvHomeRisk.DataSource = SQLDS_ListAllRiskOverdue
Case "My Risks"
grvHomeRisk.DataSource = SQLDS_ListMyRisk
Case "My Risks Overdue"
grvHomeRisk.DataSource = SQLDS_ListRiskOverdue
Case "Risks Requested to Score & Re-Score"
grvHomeRisk.DataSource = SQLDS_ListScores
Case "Risks Requested to Score"
grvHomeRisk.DataSource = SQLDS_ListRiskScores
Case "Risks Requested to Re-Score"
grvHomeRisk.DataSource = SQLDS_ListRiskReScores
End Select
grvHomeRisk.DataBind()
End Sub
My GridView...
<asp:GridView ID="grvHomeRisk" runat="server" AutoGenerateColumns="false" AllowSorting="true"
CssClass="GridMain" UseAccessibleHeader="false"
ForeColor="#333333" GridLines="None" Width="780px" BorderWidth="0px"
AllowPaging="true" PageSize="5" CellPadding="3" DataKeyNames="IDRISK">
<Columns>
<asp:CommandField ButtonType="Image" SelectText="View Risk" ShowSelectButton="True" SelectImageUrl="~/Images/button-select1.png" />
<asp:BoundField DataField="TXRISKSUMMARY" HeaderText="Risk" ReadOnly="True" />
<asp:BoundField DataField="TSRISKSTART" HeaderText="Start Date" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TSRISKREVIEW" HeaderText="Review Date" SortExpression="TSRISKREVIEW" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TXUSER_NAME_O" HeaderText="Owner" SortExpression="TXUSER_NAME_O" ReadOnly="True" />
<asp:BoundField DataField="TXDESCRIPTION" HeaderText="Risk Element" SortExpression="TXDESCRIPTION" ReadOnly="True" />
<asp:BoundField DataField="TSDATMOD" HeaderText="Date Modified" ReadOnly="True" DataFormatString="{0:dd MMM yyyy}" />
<asp:BoundField DataField="TXUSER_NAME_M" HeaderText="Modified By" ReadOnly="True" />
</Columns>
<PagerTemplate>
<table>
<tr>
<td>
<asp:Button ID="FirstButton" runat="server" CommandArgument="First" CommandName="Page" Text="<<" CssClass="buttongrid" ToolTip="First" OnClientClick="needToConfirm = false;" />
<asp:Button ID="PrevButton" runat="server" CommandArgument="Prev" CommandName="Page" Text="Previous" CssClass="button" ToolTip="Previous" OnClientClick="needToConfirm = false;" />
</td>
<td>
<asp:Label ID="lblPageCount" runat="server" CssClass="TextA12Bold" Visible="false"></asp:Label>
</td>
<td>
<asp:Button ID="NextButton" runat="server" CommandArgument="Next" CommandName="Page" Text="Next" CssClass="button" ToolTip="Next" OnClientClick="needToConfirm = false;" />
<asp:Button ID="LastButton" runat="server" CommandArgument="Last" CommandName="Page" Text=">>" CssClass="buttongrid" ToolTip="Last" OnClientClick="needToConfirm = false;" />
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>

set the value of inputbox inside a data grid through VB code

I have a asp datagrid one of the column is having one input
<asp:DataGrid ID="dgItem" runat="server" Width="100%" CssClass="TableList" AutoGenerateColumns="False" PagerStyle-Visible="False">
<Columns>
<asp:TemplateColumn HeaderText="Disc %">
<HeaderStyle HorizontalAlign="Right" CssClass="ListHeader"></HeaderStyle>
<ItemStyle HorizontalAlign="Right" Width="6%" CssClass="TdList"></ItemStyle>
<ItemTemplate>
<input class="Input" onkeypress="if((event.keyCode<48 || event.keyCode>57) && event.keyCode != 46 && event.keyCode != 45) event.returnValue=false;"
id="txtDiscRate" style="width: 100%; text-align: right" value="0.00" name="txtDiscRate"
runat="server" onchange="checkrate();">
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle Visible="False"></PagerStyle>
</asp:DataGrid>
how to set the value of that column through VB.net code
This column is the 10th cell. In the 1st cell there is a value which should be set to the 10th column
So, I've tried the following..but not working.
Dim lnDiscRate As Double
Double.TryParse(lodgGrid.Cells(1).Text, lnDiscRate)
Dim loDiscRate As HtmlInputText
For Each lodgGrid In dgItem.Items
loDiscRate = lodgGrid.Cells(10).FindControl("txtDiscRate")
loDiscRate.Value = lnDiscRate 'Not working :(
loDiscRate.Enabled = True 'this is Working..
Next
Pls Help!!
Got something else. when i do this
CType(lodgGrid.FindControl("txtDiscRate"), HtmlInputText).Value = 10 ' Working
CType(lodgGrid.FindControl("txtDiscRate"), HtmlInputText).Value = lnDiscRate ' Not Working
Implement ItemDataBound on your DataGrid and use the following
Private Sub dgItem_ItemDataBound(sender As Object, e As DataGridItemEventArgs) Handles dgItem.ItemDataBound
'Get the text value of the second cell as stated above, if you want the first use 0
Dim lnDiscRate As String
lnDiscRate = e.Item.Cells(1).Text
'set the text value of the desired input to the string found above...
CType(e.Item.FindControl("txtDiscRate"), HtmlInputText).Value = lnDiscRate
End Sub

Resources