Bind two datasources into one grid - asp.net

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.

Related

mail merge with dynamic file path

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

how to exactly transfer checked rows from gridview1 to gridview2 (both are in the same page)

currently this method is displaying in a gridview2 just the first column of the rows checked in gridview1 checkboxes but i need to display all of the columns exactly as gridview1, so how do i do it?
protected void Button1_Click2(object sender, EventArgs e)
{
List<string> lista = new List<string>();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("chk") as CheckBox;
if (chbox.Checked == true)
{
lista.Add("'" + GridView1.Rows[i].Cells[1].Text + "'");
}
}
DataTable dt = new DataTable();
GridView2.DataSource = lista;
GridView2.DataBind();
}
code to of your button will be below
protected void Button1_Click2(object sender, EventArgs e)
{
List<CopyGrid> lista = new List<CopyGrid>();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chbox = GridView1.Rows[i].Cells[0].FindControl("chk") as CheckBox;
if (chbox.Checked == true)
{
CopyGrid content = new CopyGrid();
content.Name = GridView1.Rows[i].Cells[1].Text;
content.Email = GridView1.Rows[i].Cells[2].Text;
content.City = GridView1.Rows[i].Cells[3].Text;
content.PostCode = GridView1.Rows[i].Cells[4].Text;
lista.Add(content);
}
}
// DataTable dt = new DataTable();
GridView2.DataSource = lista;
GridView2.DataBind();
}
also create one class that will store details of gridview1
public class CopyGrid
{
public string Name;
public string Email;
public string City;
public string PostCode;
}
This is just sample code you have to implement your own code.

how to get total of all column if GridView Paging is set as “True”?

this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}
Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}

Unable to serialize the session state

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You
I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

Resources