I am stack in something simple i think.
I have the following code:
public void Button1Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (FileUpload1.PostedFile.ContentType == "text/xml")
{
string filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
DataSet ds = new DataSet();
ds.ReadXml((Server.MapPath(filename)));
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
StatusLabel.Text = "Only xml files are accepted!";
}
}
public void Button2_Click1(object sender, EventArgs e)
{
}
What i want is the user the execute this code in button2
DataSet ds = new DataSet();
ds.ReadXml((Server.MapPath(filename)));
GridView1.DataSource = ds;
GridView1.DataBind();
My problem is that the variable filename is not available outside
public void Button1Click(object sender, EventArgs e)
Thanks in advance for your help!
Chris
you can persist the variable in the page ViewState like this:
private string fileName
{
get { return ViewState["fileName"] != null ? (string)ViewState["fileName"] : String.Empty; }
set { ViewState["fileName"] = value; }
}
Save the filename into Session or ViewState while uploading a file.
public void Button1Click(object sender, EventArgs e)
{
..
string filename = Path.GetFileName(FileUpload1.FileName);
...
Session["filename"]=filename;
}
Code in Button2 click handler,
public void Button2_Click1(object sender, EventArgs e)
{
if(Session["filename"]!=null)
{
string filename=Session["filename"].ToString();
DataSet ds = new DataSet();
ds.ReadXml((Server.MapPath("~/" + filename)));
GridView1.DataSource = ds;
GridView1.DataBind();
}
Actually here you can have huge amount of variants:
You can get this value from file upload control, juts simply using same method as it was used in Button1Click:
string filename = Path.GetFileName(FileUpload1.FileName);
More correctly, is to store in ViewState as it was told before.
If you want to use this in other pages, just save this to session.
Related
I have been following this tutorial to implement edit/update functionality via a modal popup form in asp.net:
http://msdnaspdotnettuto.blogspot.com/2015/01/aspnet-gridview-crud-using-twitter.html
This is my code:
public partial class GroupSummary1 : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGroupSummary();
}
}
private void LoadGroupSummary()
{
try
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}
protected void gvGroupSummary_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("detail"))
{
string code = gvGroupSummary.DataKeys[index].Value.ToString();
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
DataTable detailTable = query.CopyToDataTable<DataRow>();
DetailsView1.DataSource = detailTable;
DetailsView1.DataBind();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#detailModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
}
}
}
When I select the "detail" button on the grid view, the following error occurs:
System.ArgumentNullException HResult=0x80004003 Message=Value
cannot be null. Parameter name: source Source= StackTrace:
At this line:
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<int>("GroupID").Equals(code)
select i;
The dt object is NULL and I suspect this is the source of the problem. However, I have declared it above just as in the tutorial.
Any ideas?
Thanks
LoadGroupSummary is only firing on initial page load, not on postback. Clicking your detail button to call gvGroupSummary_RowCommand() will cause a postback.
Simply remove the if (!IsPostBack) from your page load.
protected void Page_Load(object sender, EventArgs e)
{
LoadGroupSummary();
}
EDIT:
Might be worth mentioning that if whatever data userBLL.GetGroupSummary() returns is static, you should probably only load it once. For Example:
private void LoadGroupSummary()
{
try
{
if (Session["GroupSummary"] != null)
{
dt = (DataTable)Session["GroupSummary"];
}
else
{
UserBLL userBLL = new UserBLL();
dt = userBLL.GetGroupSummary(2, 2017);
Session["GroupSummary"] = dt;
}
gvGroupSummary.DataSource = dt;
gvGroupSummary.DataBind();
}
catch (SqlException ex)
{
System.Console.Error.Write(ex.Message);
}
}
I would like to load a DataGridView from an XML file.
I put the 'load' code in a Button event like this:
private void metroButton13_Click(object sender, EventArgs e)
{
// load
DataSet dataSet = new DataSet();
dataSet.ReadXml(#"C:\temp\xml.xml");
dataGridView1.DataSource = dataSet.Tables[0];
}
And it loads correctly what I want using a const UniCode-String.
What I need now is a PopUp Window in which I can choose the file to be bound to the DataSource instead of the const "C:\temp\xml.xml" string.
Yes I know there is a lot of topic I try, but so far I'm unable to do this in my project.
You can use OpenFileDialog to select the file and pass this to ReadXml. Something like the below lines would solve your problem.
private void metroButton13_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
int size =0;
string file = string.empty;
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
if(size >0)
{
DataSet dataSet = new DataSet();
dataSet.ReadXml(file);
dataGridView1.DataSource = dataSet.Tables[0];
}
else
{
msgbox ("blank file");
}
}
DataSet dataSet = new DataSet();
OpenFileDialog sfd = new OpenFileDialog();
sfd.Filter = "XML|*.xml";
if (sfd.ShowDialog() == DialogResult.OK)
{
string file = sfd.FileName;
try
{
dt.ReadXml(file);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Actually this code solve my problem but you give me something to think just. Anyway thank you!
I am creating a website having a masterpage. I want to create a hit counter to record the number of visitor and i found a code and put it in my masterpage. The code is as:
Markup Code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="counter.ascx.cs" Inherits="counter" %>
<asp:Label ID="lblCounter" runat="server"></asp:Label>
Code Behind - C#:
protected void Page_Load(object sender, EventArgs e)
{
this.countMe();
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
private void countMe()
{
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = 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"));
}
An xml file in the root directory to make the code work. The XML file is as:
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
</counter>
But every pages within my website triggers the counter whenever i visit them. Please help me modify this code to trigger the counter only one time by one visitor.
I have decided to put the code on index page only, but still every refresh and every lick to open the index (even while staying on index page) triggers the counter.
Why not just add a session? I think it's the easiest way for an XML solution, if you saved it to SQL you could have more logic involved.
private void countMe()
{
if(Session["Counted"]==null){
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = 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"));
Session["Counted"] = "Yes";
}
}
You need to check the url of the page for the counter to hit the code. Try something like this
protected void Page_Load(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsoluteUri;
if(url.Contains("index.aspx")
{
this.countMe();
}
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
You can get the solution from Global.ascx File.
Go to code behind of Golobal.ascx.cs in your application.
Declare a variable in Global.Cs File.
And Maintain a Count in 'Session_Start' Function Of Global.ascx.cs file;
write some public method to get user count
Eg:
protected void Session_Start(Object sender, EventArgs e)
{
totalNumberOfUsers += 1;
currentNumberOfUsers += 1;
}
protected void Session_End(Object sender, EventArgs e)
{
currentNumberOfUsers -= 1;
}
public static int TotalNumberOfUsers
{
get
{
return totalNumberOfUsers;
}
}
public static int CurrentNumberOfUsers
{
get
{
return currentNumberOfUsers;
}
}
In addition to using "Session" as in prospectors example, due to the possibility of synchronization issues , don't forget to lock the DataSet before use.
private static readonly object LockObj = new object();
private static DataSet dataSet = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Counted"] == null)
{
lock (LockObj)
{
dataSet.ReadXml(Server.MapPath("~/counter.xml"));
dataSet.Tables[0].Rows[0]["hits"] = (1 + int.Parse(dataSet.Tables[0].Rows[0]["hits"].ToString())).ToString();
dataSet.WriteXml(Server.MapPath("~/counter.xml"));
dataset.clear();
}
Session["Counted"] = "true";
}
}
I created a grid view application and outside of my template I have a Add new row button. When i add a new row , it gets placed with an Edit and delete button. What I'm trying to do is when I click the add new row button, i want it to open the new row in editing mode, so no blank rows can be added with empty information. So basically if I add a new row and dont input information it wont be created.
If I need to be more thorough on my explanation please ask.
Any help will be appreciated.
Thank you
I ended up figuring out the problem on my own. It works perfect now. I as well changedup the database but I'm providing my code. Im sure there is an easier way but this was the best I could do: If you guys can provide inputs on an easier way I would appreciate it.
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
gv.DataBind();
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "", fundCode = "", BSA_CD = "", DP_TYPE = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
fundCode = d.Rows[0]["FUND_CD"].ToString();
BSA_CD = d.Rows[0]["BSA_CD"].ToString();
DP_TYPE = d.Rows[0]["DP_TYPE"].ToString();
if (transCode.Trim().Length > 0)
{
dbcon.Execute("INSERT INTO CIS.CIS_TRANS (TRANS_CD) VALUES('')", "ProjectCISConnectionString");
gv.DataBind();
}
}
gv.EditIndex = gv.Rows.Count - 1;
}
else if (e.CommandName == "Cancel")
{
DataTable d = dbcon.GetDataTable("SELECT * FROM CIS.CIS_TRANS ORDER BY ID DESC", "ProjectCISConnectionString");
string transCode = "";
if (d.Rows.Count > 0)
{
transCode = d.Rows[0]["TRANS_CD"].ToString();
if (transCode.Trim().Length == 0)
{
dbcon.Execute(string.Format("DELETE CIS.CIS_TRANS WHERE ID = '{0}'", d.Rows[0]["ID"]), "ProjectCISConnectionString");
gv.DataBind();
}
}
}
}
This is fairly simple, once you add the row:
You need to set the edit index of the newly added row:
gv.EditIndex = gv.Rows.Count-1;
Edit for OP
This is dirty code, I am just showing you what I mean and whipped it up fairly quickly.
Assume a gridview called GridView1 on your page:
namespace HelpSO3
{
public partial class _Default : System.Web.UI.Page
{
List<string> t = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string s = "hi";
t.Add(s);
GridView1.DataSource = t;
GridView1.DataBind();
Session["MyList"] = t;
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
t = (List<string>)Session["MyList"];
t.Add("Another String");
GridView1.DataSource = t;
GridView1.DataBind();
GridView1.EditIndex = GridView1.Rows.Count - 1;
GridView1.DataBind();
Session["MyList"] = t;
}
}
}
So the Button1_Click event adds a new row with the value "Another String" then we bind the grid view and set the EditIndex value to the newest row and rebind. Its that simple.
In your case your code would become:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") //- this is needed to explain that the INSERT command will only work when INSERT is clicked
{
dbcon.Execute("INSERT INTO PROJ_ASP (TRANS_CD) VALUES('')", "ProjectASPConnectionString");
gv.DataBind();
gv.EditIndex = gv.Rows.Count-1;
gv.DataBind();
}
}
I cannot get anything other than a null value from my drop down box, im trying to upload files to different directories...
public class dropDownInfo
{
public string pathName { get; set; }
public string pathValue { get; set; }
}
string uploadFolder = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// reference to directory
//DirectoryInfo di = new DirectoryInfo("//DOCSD9F1/TECHDOCS/");
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files/");
// create list of directories
List<dropDownInfo> DropDownList = new List<dropDownInfo>();
foreach (DirectoryInfo i in di.GetDirectories())
{
dropDownInfo ddInfo = new dropDownInfo();
ddInfo.pathName = i.FullName;
ddInfo.pathValue = i.FullName;
DropDownList.Add(ddInfo);
}
DropDownList1.DataSource = DropDownList;
DropDownList1.DataTextField = "pathName";
DropDownList1.DataValueField = "pathValue";
DropDownList1.DataBind();
}
}
protected void DropDownList1_IndexChanged(object sender, EventArgs e)
{
uploadFolder = DropDownList1.SelectedItem.Value;
}
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = #"\\DOCSD9F1\TECHDOCS\";
string fileName = e.UploadedFile.FileName;
//string uploadFolder = DropDownList1.SelectedValue;
//string path = (uploadDirectory + uploadFolder + "/" + fileName);
string path = Path.Combine(Path.Combine(uploadDirectory, uploadFolder), fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}
Do a check before you access the Value property.
if (DropDownList1.SelectedItem != null)
uploadFolder = DropDownList1.SelectedItem.Value;
The dropdown has no values after postback. You are only binding at first page load, then the page posts back (index changed) and the items are not re-bound.
Do you have viewstate disabled on the page or any of the controls? This could cause the issue you are describing.
Also, the local variable uploadFolder will never be preserved between post backs. You need to store it in the session or on the page somewhere.
Session["uploadFolder"] = DropDownList1.SelectedItem.Value
You need to re-set the DataSource on post back, but don't re-bind it or that will reset the selected index as well.