get selected row index of dynamic dropdown list selection - asp.net

I know the question is a little choppy and perhaps misleading,but I have a gridview with dropdownlists on the rows. I created an AddHandler and a Delegate for the SelectedIndexChanged and it gets to the sub. Here is the code for that:
AddHandler ddlmgr.SelectedIndexChanged, AddressOf ddlmgr_SelectedIndexChanged
Public Delegate Sub DropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As DropDownList_SelectedIndexChanged)
Protected Sub ddlmgr_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
End Sub
How can i get the row's Id if GridView_RowCommand is not called?

You will need to do a bit of the legwork as I cant provide 100% specifics without writing out the code and testing it on my own here, which I am unable to do at present, but the code should go along these lines.
within the ddlmgr_SelectedIndexChaged,
cast your sender to a DropDownList
access the part property of the dropdownlist.
Check it is is a GridItem (or repeateritem or whichever, you get the idea)
If so, get the items itemindex. If not access its parent property.
Continue until you find your Row object.

Hopefully this helps. If not, perhaps someone with a bit more liberal access can chime in
DropDownList ddl = (DropDownList)sender;
Control p = ddl.Parent;
//you are going to loop because the immediate
//parent may not be the repeater item but instead a
//container control of some kind (say a template)
while (p.GetType() != typeof(RepeaterItem))
{
p = p.Parent;
if (p == null) return; //we have reached the top of the control tree
}
RepeaterItem ri = (RepeaterItem)p;
int index = ri.ItemIndex
return index;

Great work
Works absolutely fine for me
DropDownList ddl = (DropDownList)sender;
Control p = ddl.Parent;
//you are going to loop because the immediate
//parent may not be the repeater item but instead a
//container control of some kind (say a template)
while (p.GetType() != typeof(RepeaterItem))
{
p = p.Parent;
if (p == null)
return; //we have reached the top of the control tree
}
RepeaterItem ri = (RepeaterItem)p;
int index = ri.ItemIndexreturn index;

DropDownList ddltxt = (DropDownList)sender;
string temp2 = ddltxt.SelectedItem.Text;
string temp3 = ddltxt.SelectedItem.Value;
string temp = ddltxt.ID.ToString();
int strlength = temp.Length;
string strLastchar = temp.Substring(strlength - 1, 1);
int intlastchar = int.Parse(strLastchar.ToString());
string commonpart = temp.Substring(0, strlength - 1);
if (intlastchar == 1)
{
string targetdropdownid = commonpart + "2";
DropDownList targetlist = (DropDownList)TableRow11.FindControl(targetdropdownid);
using (conn = new SqlConnection(ConnectionString))

Related

gridview hide columns [duplicate]

This question already has answers here:
GridView Hide Column by code
(13 answers)
Closed 8 years ago.
I have gridview and I want to hide a column after databind to gridview but I get the error below.
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"
My C# code is below,
protected void grid_all_posts_DataBound(object sender, EventArgs e)
{
if (grid_all_posts.Columns[1].Visible)
{
grid_all_posts.Columns[1].Visible = false;
}
}
// Read all posts and fill gridview
//////////////////////////////////////////////////
DbCommand dbCommand2;
dbCommand2 = db.GetStoredProcCommand("SP_Select_News");
db.AddInParameter(dbCommand2, "UserId", DbType.Guid, new Guid(Session["UserId"].ToString().Trim()));
DataSet ds = db.ExecuteDataSet(dbCommand2);
grid_all_posts.DataSource = ds;
grid_all_posts.DataBind();
//////////////////////////////////////////////////
My ASPX code,
<asp:gridview runat="server" ID="grid_all_posts" OnRowDataBound="grid_all_posts_DataBound"></asp:gridview>
What do you think the problem is? How I can hide the first column
Try like below it will work....
DbCommand dbCommand2;
dbCommand2 = db.GetStoredProcCommand("SP_Select_News");
db.AddInParameter(dbCommand2, "UserId", DbType.Guid, new Guid(Session["UserId"].ToString().Trim()));
DataSet ds = db.ExecuteDataSet(dbCommand2);
grid_all_posts.DataSource = ds;
grid_all_posts.DataBind();
**//after Databind Write the below code**
if (grid_all_posts.Columns.Count > 0)
grid_all_posts.Columns[0].Visible = false;
else
{
grid_all_posts.HeaderRow.Cells[0].Visible = false;
foreach (GridViewRow gvr in grid_all_posts.Rows)
{
gvr.Cells[0].Visible = false;
}
}
A simple and versatile approach for this has been bugging me for ages - something that does not require any kind of column counting, I eventually found it today; DataControlFieldCell.ContainingField.HeaderText
Private Sub GridView_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView.RowDataBound
For Each r As GridViewRow In GridView.Rows
If r.RowType = DataControlRowType.DataRow Then
For Each c As DataControlFieldCell In r.Cells
Dim h As String = c.ContainingField.HeaderText
If h <> "ColumnName" Then c.ContainingField.Visible = False
If IsNumeric(c.Text) Then c.Text = Format(CInt(c.Text), "#,##0")
Next
End If
Next
End Sub
I loop through the DataControlFieldCells as I perform some formatting on the values in my fields as well (as illustrated above) but you could just loop through the header I imagine if you wanted to cut it down further still.
See msdn for more details.

Count visitor of one page in asp.net

I have a page that contains a record of a database. I want to count number of visits of that page . I use codes below to counts number of visits of page by increment view field of record. but this increment view randomly. for example when I refresh page the view increment 20 !.
my codes for this page is:
protected void Page_Load(object sender, EventArgs e)
{
da db = new da();
string str = "select views from newstxt where id=" + Request.Params["id"].ToString();
DataTable dt = new DataTable();
dt = db.select(str);
int view = Int32.Parse(dt.Rows[0][0].ToString());
//increment
view++;
//
str = "update newstxt set views=N'{0}' where id=" + Request.Params["id"].ToString();
str = string.Format(str, view);
db.docom(str);
}
There are couple of ways for this approach
simple approach would be using a view state
declare a Property like
public int ViewCount
{
get { return (int)ViewState["viewcount"]; }
set { ViewState["viewcount"] = value; }
}
use like ViewCount++; on page load and to get value int value = ViewCount
i hope this helps !!!
Protected Sub Page_Load(sender As Object, e As EventArgs)
Me.countMe()
Dim tmpDs As New DataSet()
tmpDs.ReadXml(Server.MapPath("~/counter.xml"))
lblCounter.Text = tmpDs.Tables(0).Rows(0)("hits").ToString()
End Sub
Private Sub countMe()
Dim tmpDs As New DataSet()
tmpDs.ReadXml(Server.MapPath("~/counter.xml"))
Dim hits As Integer = Int32.Parse(tmpDs.Tables(0).Rows(0)("hits").ToString())
hits += 1
tmpDs.Tables(0).Rows(0)("hits") = hits.ToString()
tmpDs.WriteXml(Server.MapPath("~/counter.xml"))
End Sub
XML
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
Nothing seems to be wrong with your code but it seems like there is something wrong your Request.Params. Are you using query string, if it is then i would suggest you to use Request.QueryString instead. Also, what you want only if to update the count then you can avoid select query and reduce your code to:
da db = new da();
String str = "UPDATE newstxt SET views = views + 1 WHERE id=" + Request.QueryString["id"].Trim();
db.docom(str);

Enable hyperlink field in gridview while all other controls are disabled

I have to disable all the controls on my gridview for business purposes.
Me.gvLineItems.Enabled=False
However, I need to enable one hyperlink field enabled so I tried this:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim hrf As HyperLink
hrf = CType(Row.Cells(16).Controls(0), HyperLink)
hrf.Enabled = True
Next
I debug the code and it sets the hyperlink field enabled to true, but when I run the app the field is still disabled...
But If I get rid of the Me.gvLineItems.Enabled=False just comment that out and change my code to DISABLE the hyperlink field:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim hrf As HyperLink
hrf = CType(Row.Cells(16).Controls(0), HyperLink)
hrf.Enabled = False
Next
This works fine...
But that is not what I need :(, just trying to reenable the link field...
Edit
I also tried this in the rowdatabound event:
If Me.gvLineItems.Enabled = False Then
For i As Integer = 0 To e.Row.Cells.Count - 1
If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then
Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink)
h.Enabled = True
Exit For
End If
Next
End If
I got it with this:
For i As Integer = 0 To e.Row.Cells.Count - 1
If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then
Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink)
h.Enabled = True
Exit For
Else
e.Row.Cells(i).Enabled = False
End If
Next
You'll need to use some type of recursive logic to loop through all the cells and disable the controls, with a condition to exclude HyperLink controls. By disabling the controls at the row level, the enabled state of the parent container (i.e. GridViewRow) will always override the enabled state of the control.
I would add some recursive logic in the RowDataBound event. Try something like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DisableControls(e.Row);
}
private void DisableControls(WebControl parentCtrl)
{
if (parentCtrl.HasControls())
{
foreach (WebControl ctrl in parentCtrl.Controls)
{
ctrl.Enabled = ctrl is HyperLink;
DisableControls(ctrl);
}
}
else
{
parentCtrl.Enabled = parentCtrl is HyperLink;
}
}

Positioning of DDL items?

i have a dropDownList which gets its data from a database. Now after the data has bound, i programmatically add another listItem to the ddl, like so:
protected void ddlEffects_DataBound(object sender, EventArgs e)
{
DropDownList ddl = dwNewItem.FindControl("ddlEffects") as DropDownList;
ddl.Items.Add(new ListItem("","0")); //Adds an empty item so the user can select it and the item doesnt provide an effect
}
It all works, but the problem is that the newly added listItem appears at the bottom of the DDL. I want it to be the first item. I tried making the value 0, but its still at the bottom. Is there any way to put it at the top?
Thanks!
Check into the ddl.Items.Insert method that will allow you to insert items at a specific location.
Like this for example:
using (Entities db = new Entities())
{
ddlDocumentTypes.DataSource = (from q in db.zDocumentTypes where (q.Active == true) select q);
ddlDocumentTypes.DataValueField = "Code";
ddlDocumentTypes.DataTextField = "Description";
ddlDocumentTypes.DataBind();
ddlDocumentTypes.Items.Insert(0, "--Select--");
ddlDocumentTypes.Items[0].Value = "0";
}
Which using EF loads the DDL with items for the database, and then inserts at position zero a new item.

ASP.Net Grid View rolling total in Gridview

I have seen several tutorials on how to achieve this.
However in my opinion they require a lot of prior knowledge on how to programatically refer to each item.
Does anyone have a link to or can create a relatively basic example of how to achive a running total in the footer for an ASP:Gridview?
This is what I use:
protected void InvoiceGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var invoice = (Invoice) e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.Header)
{
totalAmt = 0;
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
totalAmt += invoice.Amount;
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
var amountTotalLabel = (TextBox) e.Row.FindControl("AmountTotalTextBox");
amountTotalLabel.Text = totalAmt.ToString("0.00");
}
}
TotalAmt is protected instance variable on the page. Not sure if it's what you were looking for based on your comment about "programmatic knowledge." But it works and is fairly straight-forward. The gridview is bound to a List<Invoice> in this case.
Add the footer Template and on the RowDataBound, have a global variable to store the summation sum,
At the e.Row.RowType = DataControlRowType.DataRow type do the summation , and # the e.Row.RowType = DataControlRowType.Footer store the vale in the appropriate cell
for further info look # MSDN LINK
This is how I do it. Very easy. You just sum the row that has your numbers in it and place it in the footer.
((Label)GridView.FooterRow.Cells[1].FindControl("your_label")).Text = ds.Tables[0].Compute("sum(Column_name)", "").ToString();
I think the method I use is pretty basic and doesn't require programatically referring to columns in the Gridview, if that's what you mean. That's one of the nice parts is that once you get the back-end functions written, you can add totals to any Gridview by only editing the .aspx file.
In your GridView, make the column like this:
<asp:TemplateField HeaderText="Hours">
<ItemTemplate><%#DisplayAndAddToTotal(Eval("Hours").ToString(), "Hours")%></ItemTemplate>
<FooterTemplate><%#GetTotal("Hours")%></FooterTemplate>
</asp:TemplateField>
The second parameter to DisplayAndAddToTotal can be any string you want as long as you use the same string in GetTotal. I usually just use the field name again though. Here are the two functions used, DisplayAndAddToTotal and GetTotal. They use a Hashtable to store the totals so that it works with any number of columns you want to add up. And they also work with counting the number of "True"s for a Boolean field.
Protected total As Hashtable = New Hashtable()
Protected Function DisplayAndAddToTotal(itemStr As String, type As String) As Double
Dim item As Double
If itemStr = "True" Then
item = 1
ElseIf Not Double.TryParse(itemStr, item) Then
item = 0
End If
If total.ContainsKey(type) Then
total(type) = Double.Parse(total(type).ToString()) + item
Else
total(type) = item
End If
Return item
End Function
Protected Function GetTotal(type As String) As Double
Try
Dim result As Double = Double.Parse(total(type).ToString())
Return result
Catch
Return 0
End Try
End Function

Resources