I am getting an error with an aspx Upload Control & Drop Down List on a single aspx page.
Here is the error...
Object reference not set to an instance of an object.
Here is my code for the on_submit...
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = "//DOCSD9F1/TECHDOCS/";
string uploadFolder = DropDownList1.SelectedItem.Text;
string fileName = e.UploadedFile.FileName;
string path = (uploadDirectory + uploadFolder + fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}`
here is my code for creating the drop down list...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files");
DropDownList1.DataSource = di.GetDirectories();
DropDownList1.DataBind();
foreach (DirectoryInfo i in di.GetDirectories())
{
DropDownList1.DataTextField = i.FullName;
DropDownList1.DataValueField = i.FullName;
}
}
}`
You might want to try this:
if(!Page.IsPostBack){
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files");
DirectoryInfo[] diArr = di.GetDirectories();
DropDownList1.DataSource = diArr;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
}
And get the selected value like:
string uploadFolder = DropDownList1.SelectedValue;
FYI: Make sure there are proper slashes(/) in the path you are creating while uploading the file.
Related
I had a problem generating a word template because I wanted it to be selected dynamically with ddlTemplate when selected to write in it with the merge field in the word template.
this is my code:
public partial class unTemplate : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)// call the method for ONLY first time for visitor
{
{
populateDdlInstitution();
}
}
}
protected void populateDdlInstitution()
{
CRUD myCrud = new CRUD();
string mySql = #"select institutionid, institution from institution";
SqlDataReader dr = myCrud.getDrPassSql(mySql);
ddlInstitution.DataTextField = "institution";
ddlInstitution.DataValueField = "institutionid";
ddlInstitution.DataSource = dr;
ddlInstitution.DataBind();
}
protected void ddlInstitution_SelectedIndexChanged(object sender, EventArgs e)
{
// call a method to populate the template ddl
populateDdlTemplate();
}
protected void populateDdlTemplate()
{
CRUD myCrud = new CRUD();
string mySql = #"select internDocId, DocName
from internDoc
where institutionId = #institutionId";
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
ddlTemplate.DataTextField = "DocName";
ddlTemplate.DataValueField = "internDocId";
ddlTemplate.DataSource = dr;
ddlTemplate.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
CRUD myCrud = new CRUD();
string mySql = #"select* from intern
where institutionId = #institutionId"/*+#"select internDocId,DocName from internDoc where internDocId=internDocId"*/;
Dictionary<string, object> myPara = new Dictionary<string, object>();
myPara.Add("#institutionId", ddlInstitution.SelectedItem.Value);
//myPara.AsEnumerable(#"internDocId");
SqlDataReader dr = myCrud.getDrPassSql(mySql, myPara);
gvData.DataSource = dr;
gvData.DataBind();
}
protected void btnGenerateTemplate_Click(object sender, EventArgs e)
{
wordT();
}
private static DataTable GetRecipients()
{
//Creates new DataTable instance.
DataTable table = new DataTable();
//Loads the database.
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + #"../../CustomerDetails.mdb");
//Opens the database connection.
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from intern", conn);
//Gets the data from the database.
adapter.Fill(table);
//Releases the memory occupied by database connection.
adapter.Dispose();
conn.Close();
return table;
}
public void wordT()
{
for (int i = 0; i <= gvData.Rows.Count - 1; i++)
{
String internId = gvData.Rows[i].Cells[0].Text;
String fullName = gvData.Rows[i].Cells[7].Text;
String cell = gvData.Rows[i].Cells[8].Text;
String email = gvData.Rows[i].Cells[9].Text;
Syncfusion.DocIO.DLS.WordDocument document = new Syncfusion.DocIO.DLS.WordDocument(Server.MapPath(getPath()));
//Deleting null fields
document.MailMerge.RemoveEmptyParagraphs = true;
string[] fieldNames = new string[] { "fullName", "internId", "email", "cell" };
string[] fieldValues = new string[] { fullName, internId, email, cell };
// mail merge
document.MailMerge.Execute(fieldNames, fieldValues);
//Saves
document.Save(Server.MapPath("~/myDoc/" + email + ".docx"));
document.Close();
}
// pass message to user notifying of successfull operation
lblOutput.Text = "Word Doc output generated successfully!";
}
public string getPath()
{
DirectoryInfo di = new DirectoryInfo(#"C:\projects\unSupervisorApp\Uploads\");
foreach (var d in di.EnumerateDirectories())
{
foreach (var fi in d.EnumerateFileSystemInfos())
{
if (fi.Name == (ddlTemplate.DataTextField))
{
return fi.FullName.Replace(fi.Name, "");
}
}
}
return di.FullName;
}
}//cls
the problem:
1-'C:/projects/unSupervisorApp/Uploads/' is a physical path but was expected to be a virtual path.
2- and sometime it gives me that it i can not find the file in EnumerateDirectories.
but i get the first one the most.
getFile
getPath
path of folder + ddlselectedItem.text
I need to use a the session dataTable email value for the #email and the base from the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
string str;
protected void Submit_Click(object sender, EventArgs e)
{
if (CheckBox9.Checked == true)
{
str = str + CheckBox9.Text + "x";
}
}
SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set Question1 = #str WHERE email = #email AND Base = #base;";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#email", Session.dt.email);
cmd.Parameters.AddWithValue("#str", str);
cmd.Parameters.AddWithValue("#base", DropDownList1.base);
}
}
Your syntax for reading the value out of Session is wrong, you cannot use Session.dt.email.
You need to read the DataTable out of Session and cast it to a DataTable, like this:
DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
theDataTable = Session["dt"] as DataTable;
}
string email;
// Verify that the data table is not null
if(theDataTable != null)
{
email = dataTable.Rows[0]["Email"].ToString();
}
Now you can use the email string value in your SQL command parameters, like this:
cmd.Parameters.AddWithValue("#email", email);
UPDATE:
You will want to wrap your drop down list binding in Page_Load with a check for IsPostBack, because as your code is posted it will bind the drop down list every time the page loads, not just the first time, thus destroying whatever selection the user made.
Instead do this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
}
Now your base value in your database parameter logic should be the value the user selected.
I am trying to select a user from my default_information.aspx.cs page and display that user information on my registration.aspx page where I already created a registration form.
I am getting System.NullReferenceException:Object reference not set to an instance of an object error. Please help me. I've given the main part of it. I debugged it. I found every data is selected from my DB in string strusername,strpassword. But code breaks on usernametxt.Text = strusername; when i try to show username or password on that text field.
default_information contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{
registration objdef = new registration();
string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
objdef.displayuser(username);
}
protected void update_Click(object sender, EventArgs e)
{
Response.Redirect("registration.aspx");
}
registration.aspx contains
protected void register_Click(object sender, EventArgs e)
{
user objuser = new user();
objuser.username = usernametxt.Text;
objuser.password = passwordtxt.Text;
objuser.email = emailtxt.Text;
objuser.Save();
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}
user class contains
public class user
{
public void Save()
{
clssqlserver obj = new clssqlserver();
obj.insertuser_info(Username,Password,Email);
}
public DataSet profile(string username)
{
clssqlserver obj = new clssqlserver();
return obj.getalluser_info(username);
}
}
clssqlserver contains
public DataSet getalluser_info(string username)
{
string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string command = "Select * from login_donor where username='" + username + "' ";
SqlCommand objcommand = new SqlCommand(command, objconnection);
DataSet objdataset = new DataSet();
SqlDataAdapter objadapter = new SqlDataAdapter(objcommand);
objadapter.Fill(objdataset);
objconnection.Close();
return objdataset;
}
public bool insertuser_info(string username,string password,string email)
{ string connectionstring = "Data Source=localhost\\mssql;Initial Catalog=blooddb;Integrated Security=True";
SqlConnection objconnection = new SqlConnection(connectionstring);
objconnection.Open();
string strInsertCommand = "insert into login_donor values('"+ username +"','"+ password + "','"+email+"')";
SqlCommand objcommand = new SqlCommand(strInsertCommand, objconnection);
objcommand.ExecuteNonQuery();
objconnection.Close();
return true;
}
It looks like you are using the asp.net create user wizard control.Because your controls are buried inside another container, you have to be rewarded after some little excavation..Lets start digging......
Using the wizard which is already accessible locate your text box
TextBox usernametxt= (TextBox)CreateUserWizard.FindControl("usernametxt");
usernametxt.Text = strusername;
Hope this will help.
You should check this line
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
you are trying to access directly objDataset.Tables[0], what if there is no user with the supplied username to this method getalluser_info(string username), will the dataset fill the table.
you should first check whether there is any table in the dataset or not.
hope this helps
well i ve found the solution...i was passing Data Between Webforms in worng way..here is the link which helps me: http://dotnetslackers.com/community/blogs/haissam/archive/2007/11/26/ways-to-pass-data-between-webforms.aspx
here is the solution
default_information.aspx contains
protected void gridviewprofile_SelectedIndexChanged(object sender, EventArgs e)
{ string username = gridviewprofile.Rows[gridviewprofile.SelectedIndex].Cells[1].Text;
Response.Redirect("registration.aspx?id="+username);
}
registration.aspx contains:
protected void Page_Load(object sender, EventArgs e)
{
string queryStringID = Request.QueryString["id"];
displayuser(queryStringID);
}
public void displayuser(string username)
{ user obj = new user();
DataSet objDataset = obj.profile(username);
string strusername = objDataset.Tables[0].Rows[0][0].ToString();
string strpassword = objDataset.Tables[0].Rows[0][1].ToString();
string stremail = objDataset.Tables[0].Rows[0][2].ToString();
usernametxt.Text = strusername;
passwordtxt.Text = strpassword;
emailtxt.Text = stremail;
}
I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.
I have two input controls through which I need to browse and upload the documents.
Below is my ascx
I need to have both teh files uploaded in the gridview.
Below is the code on how I am trying to achieve this.I am creating a datatable for the first upload and then a second datatable for the second upload, and then merging the twodatables into a new combined one and assigning that as the datasource for the gridview.
namespace Sharepoint.WebParts.Upload_WebPart
{
public partial class Upload_WebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
this.btnUpload.Click += new EventHandler(btnUploadUploadClick);
this.uploadsupport.Click+=new EventHandler(uploadsupport_Click);
this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
this.dgdUpload.RowDeleting += new GridViewDeleteEventHandler(dgdUpload_RowDeleting);
}
protected void btnUploadUploadClick(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
string x = Path.GetExtension(fileName);
if (fileName != "")
{
if (x == ".zip")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(inputFile.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (inputFile.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + _newfilePath;
inputFile.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, length);
lblMessage.Text = "Successfully Added in List";
}
else
{
lblMessage.Text = "Please upload a zip file";
return;
}
}
else
{
lblMessage.Text = "Select a File";
return;
}
}
private void AddMoreColumns()
{
dt = new DataTable("DT");
dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FilePath", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileSize", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("KB", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["DT"] = dt;
}
private void AddRow(string file, string path, double length)
{
dt = (DataTable)Page.Session["DT"];
if (dt == null)
{
AddMoreColumns();
}
dr = dt.NewRow();
dr["FileName"] = file;
dr["FilePath"] = path;
dr["FileSize"] = Convert.ToString(length);
dr["KB"] = "KB";
dt.Rows.Add(dr);
Page.Session["DT"] = dt;
}
Similary i add rows to the datatable dt1.
protected void bindgridview()
{
dt = (DataTable)Page.Session["DT"];
dt1 = (DataTable)Page.Session["DT1"];
joineddt = (DataTable)Page.Session["Files"];
if (joineddt == null)
{
joineddt = dt.Copy();
joineddt.Merge(dt1);
}
this.dgdUpload.DataSource = joineddt;
this.dgdUpload.DataBind();
Page.Session["Files"] = joineddt;
}}
}
Please help me to correct this , also is there a simple way to achieve this.
You can't databind to more than one data source at the same time. If the datatable joineddt does not have SupportName in it then your code would not work.
Rather than trying to try an finagle 2 data sources into one GridView, you should create one data source that has all the data you expect to display in a row of the GridView in one row of the data source.