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);
Related
I want to delete a row in GridView and database as well.. I already have a stored procedure for the delete, the method is also created, but my problem is how can i use Two datakeys for my where clause. I've search and saw a lot of answers but they are using CommandArgument and that is applicable only in 1 datakeys.
I want something like this.
DELETE FROM TableName WHERE ID = Variable1 AND Name = Variable2
What i want is how can i retrieve the values of 2 datakeys in GridView if i set DataKeys like: DataKeys="ID, Name"
Any help would be appreciated.
Thanks
(if I correctly understood you)
stored procedure
Create Procedure [dbo].[Procedure_Name](
#Variable1 type(),
#Variable2 type() --you can add as many variables as you want, but then you have to add them in c# code as a parameters.
) as
delete from Table_Name
where Table_Name.Variable1 = #Variable1 AND Table_Name.Variable2 = #Variable2
with button in aspx code
<asp:Button ID="btnDeleteSomething" runat="server" Text="Delete Something" OnClick="btnDeleteSomething_Click"/>
then in c# codebehind
protected void btnDeleteSomething_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_NAME"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("Procedure_Name", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
cmd.Parameters.Add("#Variable1", SqlDbType.VarChar, 70(its example with varchar)).Value = Variable1.Text(every Textbox, or label, or dropdownlist)
cmd.Parameters.Add("#Variable2", SqlDbType.Int).Value = Session["UserID]" - For example if u want do delete with parameter focused on user;
try
{
int rows = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
}
And it works fine without Datakeys at all. If u want to do it "with" then u have to add ControlParameter in your SqlDataSource. Hope it's going to help you.
Finally i found the solution on this link:
http://www.aspsnippets.com/Articles/Using-Multiple-DataKeyNames-DataKeys-in-ASPNet-GridView-with-examples.aspx
here is what exactly im looking for..
Dim rowIndex As Integer = TryCast(TryCast(sender, ImageButton).NamingContainer GridViewRow).RowIndex
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(rowIndex).Values(0))`
Dim Name As String = GridView1.DataKeys(rowIndex).Values(1).ToString()`
Thanks
I have created a textBox in the server side(vb.net) like this:
Dim r As New TableRow
Dim c As New TableCell
Dim txt As New TextBox
For i = 1 To 10
c = New TableCell
txt = New TextBox
txt.ID = "recev" & i
txt.ClientIDMode = UI.ClientIDMode.Static
Next
This create me all the textBox in my page.
Now the user need to enter numbers in the textBox and press on OK button.
My problem is that I don't know how to get the numbers.
If I do in the html <form> so I can do this:
For i = 1 To 10
txt = "recev" & i & ""
Request.Form(txt)
Next
and it's work. But I can't use <form> because of other reasons.
Can I use something else to get the data the user insert?
Thanks!
For example, you could use Javascript, in this way:
Event 'click' of your button: javascript:process_stuff();
Your javascript, would be something like this:
function process_stuff(){
var your_values = [];
for (var indice = 1; indice <= 10 ; indice++) {
if ($("#recev" + indice).length){
your_values[indice ] = $("#recev" + indice).val();
}
PageMethods.PM_receipt_info(your_values);
}
Server side:
<WebMethod()> _
Public Shared Sub PM_receipt_info(aValues)
for each sValue as String in aValues debug.print(sValue ) next
Where aValues is an array with the textboxes values'.
Another try: if you need a postback, can do it JS __doPostBack ('',params), passing that values sepparated with character , etc.
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.
I am reading data from an excel sheet and displaying it in a data gridview.There are some date columns in the excel.So when i read the data from the excel and bind it to the dataGridView.The date is displayed in the format "02/02/2009 12:00:00 AM" but the actual data in the excel column is in the format "2/2/2009".So how to change the date format in the datagridview.
Since i am binding the data from the dataset i dont have any template columns or bound column set so i dont know where to set the HtmlEncode="False" DataFormatString = "{0:T}"
Is there any way to do this.Please help me.
Please find the below code sample.
string OleDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+ FileUpload1.PostedFile.FileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
string strSheetName = "Sheet1";
OleDbConnection oledbConnection;
OleDbCommand oledbCommand;
OleDbDataAdapter oledbAdapter;
oledbCommand = new OleDbCommand();
oledbAdapter = new OleDbDataAdapter();
DataSet dsExcellData = new DataSet();
oledbConnection = new OleDbConnection(OleDbConnection);
oledbConnection.Open();
oledbCommand.Connection = oledbConnection;
oledbCommand.CommandText = "Select * from [" + strSheetName + "$]"; // i want to find this sheet name
oledbAdapter.SelectCommand = oledbCommand;
oledbAdapter.Fill(dsExcellData);
oledbConnection.Close();
GridView1.DataSource = dsExcellData.Tables[0];
GridView1.DataBind();
==========================================================
I tried the
dsExcellData.Tables[0].Rows[rowcount]["date_column"].ToString()] = dsExcellData.Tables[0].Rows[rowcount]["date_column"].ToString()].ToString("d");
but the value is not getting assigned as "mm/dd/yyyy" It is also taking the time default time again (mm/dd/yyyy hh:mm:ss AM).
=============================================================
I am just assigning the data set to the gridview.The problem is the dataset is reading the date column in the format mm/dd/yyyy hh:mm:ss AM.I am unable to change the data in the dataset also.
=============================================================
Finaly i got the answer from ScottE:
we have to add the below code in the itemdatabound of the datagridview :
protected void dgValidatedData_ItemDataBound1(object sender, DataGridItemEventArgs e)
{
for (int i = 0; i <= e.Item.Cells.Count - 1; i++)
{
System.DateTime cellDate = default(System.DateTime);
if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate))
{
e.Item.Cells[i].Text = string.Format("{0:d}", cellDate);
}
}
}
Ok, try this, where "Item" is the column name (could be multiple) that is a date that needs formatting. This is of course vb.net, but you can sort that out. I'm sure there's a better way, but this works.
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To e.Row.Cells.Count - 1
If gv.HeaderRow.Cells(i).Text = "Item" Then
e.Row.Cells(i).Text = String.Format("{0:d}", CType(e.Row.Cells(i).Text, Date))
End If
Next
End If
End Sub
Or, if you don't know what columns will have dates, the following will work as well:
Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
For i As Integer = 0 To e.Row.Cells.Count - 1
Dim cellDate As Date
If Date.TryParse(e.Row.Cells(i).Text, cellDate) Then
e.Row.Cells(i).Text = String.Format("{0:d}", cellDate)
End If
Next
End If
End Sub
If you're binding it as a asp:BoundField you'll need to set htmlencode to false.
<asp:BoundField HtmlEncode="false" DataField="Blah" DataFormatString="{0:d}" />
Date format you should define in your GridView column. For example:
<asp:GridView>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Date", "{0:T}") %>'></asp:Label>
</ItemTemplate>
...
</asp:GridView>
Here is a solution using a custom control that derives from GridView:
using System;
using System.Collections;
using System.Web.UI.WebControls;
namespace CustomControls {
public class FormattedGridView : GridView {
protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource) {
// Call base method and return the collection as an ArrayList
var columns = (ArrayList) base.CreateColumns(dataSource, useDataSource);
for (var i = 0; i < columns.Count; i++) {
var agf = columns[i] as AutoGeneratedField;
if (agf != null && agf.DataType == typeof(DateTime)) {
// create a new column because the AutoGeneratedField does not support
// the modification of the DataFormatString property
var bf = new BoundField();
// copy some of the original properties
bf.DataField = agf.DataField;
bf.HeaderText = agf.HeaderText;
bf.HtmlEncode = false;
// set the format for the DateTime types
bf.DataFormatString = "{0:T}";
// replace the existing auto-generated colums
columns[i] = bf;
}
}
return columns;
}
}
}
Finaly i got the answer from ScottE:
we have to add the below code in the itemdatabound of the datagridview :
protected void dg_ItemDataBound1(object sender, DataGridItemEventArgs e)
{
for (int i = 0; i <= e.Item.Cells.Count - 1; i++)
{
System.DateTime cellDate = default(System.DateTime);
if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate))
{
e.Item.Cells[i].Text = string.Format("{0:d}", cellDate);
}
}
}
But the above code will check all the data that is bound to the datagrig.It will try to parse the data as datetime in the cell.If it is a valid datetime then it will convert the data into the format which we applied.
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))