Table Format From Excel To Gridview ? In Asp.Net? - asp.net

In web application [asp.net], i am trying to get the excel data in gridview. It is working fine, but the format of the table in gridview is different from the excel. I mean format of the table is different from excel to gridivew. I am placing the screen shot please find them First is Excel Format :
second one is Gridview Screent shot which is in .aspx page.
Please help me for formating the table design. Thank you.

Try from this link: http://www.dotnetcurry.com/ShowArticle.aspx?ID=138In one video of learning Linq I saw this tag but not remember this perfectly. But I test this, also you can make table with your linq code.Have good time!

Try this code to import excel to Gridview:
using System.Data;
public partial class _Default : System.Web.UI.Page
{
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//Check file is available in File upload Control
if (FileUpload1.HasFile)
{
//Store file name in the string variable
string filename = FileUpload1.FileName;
//Save file upload file in to server path for temporary
FileUpload1.SaveAs(Server.MapPath(filename));
//Export excel data into Gridview using below method
ExportToGrid(Server.MapPath(filename));
}
}
void ExportToGrid(String path)
{
OleDbConnection MyConnection = null;
DataSet DtSet = null;
OleDbDataAdapter MyCommand = null;
//Connection for MS Excel 2003 .xls format
MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");
//Connection for .xslx 2007 format
// MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path + "';Extended Properties=Excel 12.0;");
//Select your Excel file
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
DtSet = new System.Data.DataSet();
//Bind all excel data in to data set
MyCommand.Fill(DtSet, "[Sheet1$]");
dt = DtSet.Tables[0];
MyConnection.Close();
//Check datatable have records
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
//Delete temporary Excel file from the Server path
if(System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
}
}

One of the main visible problem is your Excel spreadsheet has sub tables (for example, Cargo Qty). In 'pure' html, this can be done using COLSPAN or ROWSPAN, but with the GridView, it's not that easy, unless you create sub gridviews, like this:
<asp:GridView runat="server" ...>
<Columns>
<asp:BoundField HeaderText="MyHeader" DataField="MyField1"... />
...
<asp:TemplateField HeaderText="MySubGridHeader">
<asp:GridView runat="server" ...> // need to databind this
<Columns>
<asp:BoundField HeaderText="MySubHeader1" DataField="MyField2"... />
<asp:BoundField HeaderText="MySubHeader2" DataField="MyField3"... />
</Columns>
</asp:GridView>
</asp:TemplateField>
</Columns>
</asp:GridView>
Otherwise I suggest you go for commercial packages which can display advanced grids, such as this one for example: SPREAD (note: I'm not affiliated and I have not tested it).

Related

Display the image using Eval function in asp.net

I would like to display the image which i have stored as byte in Sql Table.
ItemTemplate code
ImageUrl=<%# Eval("Image")%>
Image is the byte from sql server. In my application couldn't able to show the picture from server.
SQL Schema : [Image] [image] NULL
Please suggest, how to display the image.
As if you have tried, you might have got some useful links. However here you go.
STEPS:-
1.To retreive Images from database, first you change your datatype from Image to nvarchar(550)
2.You need to write code fetching images on the basis of ID
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ImageID"] != null)
{
string strQuery = "select ImageName, ImagePath, ImageData from youtableName where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);
DataTable dt = GetData(cmd);
if (dt != null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["ImageName"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}
}
GetData will be your datatable value which will be coming from the database.
To Display the image on the aspx page I have used ASP.Net Image Control refer below.
<asp:image id="Image1" runat="server" imageurl="ImageCSharp.aspx?ImageID=1" />
<asp:image id="Image2" runat="server" imageurl="ImageCSharp.aspx?ImageID=2" />
<asp:image id="Image3" runat="server" imageurl="ImageCSharp.aspx?ImageID=3" />
Here is your complete reference:-
Display Images from the database using asp.net

Showing RDLC report in Asp.Net with report viewer

Am using VS 2010 and created a sample web application. Added a dataset and report and created an SP which just return one row. No variables included as of now. Just simple SP w/o any parameters. In the web app, added an aspx page and in that page added a report viewer control.
My Aspx page goes as below:
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana"
Font-Size="8pt" InteractiveDeviceInfos="(Collection)"
WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt">
</rsweb:ReportViewer>
Code behind goes as below:
protected void Page_Load(object sender, EventArgs e)
{
ReportViewer1.Visible = true;
ReportDataSource dataSource = new ReportDataSource("DataSet1", LoadData().Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(dataSource);
ReportViewer1.LocalReport.Refresh();
}
private DataSet LoadData()
{
var dataset = new DataSet();
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["CString"].ConnectionString))
{
var command = new SqlCommand("[spSampleReport]")
{
Connection = con,
CommandType = CommandType.StoredProcedure
};
var adap = new SqlDataAdapter(command);
con.Open();
adap.Fill(dataset, "DataSet1");
}
return dataset;
}
In my web config, have added following in httphandlers section:
When Running, there is nothing shown on the page. Even the report viewer toolbars are not shown.
I am no ReportViewer expert but I think you need an .rdlc to tell the report viewer what to render.
ReportViewer.LocalReport.ReportPath = Server.MapPath(string.Format(#"~\Reports\Definitions\{0}.rdlc", reportName));
Make sure the DataSet name in the .rdlc is the same as the DataSource specified when you create you ReportDataSource
I found a good example to generate rdlc reports in asp.net with code example
http://www.dotnetsharepoint.com/2013/09/how-to-create-rdlc-reports-in-aspnet.html#.UjhvAsafh88

how to set column as readonly in gridview

I am using a gridview Edit to edit the values i have in my gridview, when i press edit, all columns can be edited, i would like that one of the columns is not allowed to be edited.
Is there any way i can do this?
This is my aspx code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="True"
onrowdeleting="GridView1_RowDeleting" AutoGenerateEditButton="True"
onrowediting="GridView1_RowEditing"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowupdating="GridView1_RowUpdating" >
</asp:GridView>
This is my aspx.cs code:
public void loadCustomer()
{
SqlConnection objConnection = new SqlConnection("Data Source=localhost;Initial Catalog=SampleApplication;Integrated Security=True");
objConnection.Open();
SqlCommand objCommand = new SqlCommand();
objCommand.CommandText = "Select * from Customer";
objCommand.Connection = objConnection;
objCommand.ExecuteNonQuery();
DataSet objds = new DataSet();
SqlDataAdapter objadap = new SqlDataAdapter(objCommand);
objadap.Fill(objds);
GridView1.DataSource = objds.Tables[0];
GridView1.DataBind();
objConnection.Close();
}
RowDataBound event of gridView1
((BoundField)gridView1.Columns[columnIndex]).ReadOnly = true;
I know this is really old but I need to put the answer here for others who shared my issue. Regardless, I've been struggling with this non-stop for a couple of days now. Everyone seems to be posting code for VB, when your problem is clearly posted in C#.
What you're looking for is:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[columntobedisabled].Enabled = false;
}
where 'columntobedisabled' is index number of the column to be disabled...eg. 1
In case of C# Website or WebForm enter the following code in Page_Load() in code behind file
protected void Page_Load(object sender, EventArgs e)
{
// Your code
((BoundField)GridView1.Columns[columnIndex]).ReadOnly = true;
}
Doing this will also help in overcoming the error
System.ArgumentOutOfRangeException: 'Specified argument was out of the range of valid values. Parameter name: index'
You need to give rights "ReadOnly= true" to that column which you not like to be edit.
e.g .
GridView1.columns[1].ReadOnly= true;
You can use this line in RowDataBound event of GridView.

Displaying data dynamicall through report viewer in asp.net

Hi all,
I want to display data generated by a query in a report dynamically. I have written the following code in page load event:
protected void Page_Load(object sender, EventArgs e)
{
string sqlQuery = "select * from Login";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RosterConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, con);
DataTable dt = new DataTable();
da.Fill(dt);
ReportDataSource rds1 = new ReportDataSource("Reports_Login", dt);
DReportViewer.Reset();
DReportViewer.LocalReport.ReportPath = Server.MapPath("MyReport.rdlc");
DReportViewer.LocalReport.DataSources.Clear();
DReportViewer.LocalReport.DataSources.Add(rds1);
DReportViewer.DataBind();
DReportViewer.LocalReport.Refresh();
}
The following code is written in aspx file:
<form id="form1" runat="server">
<div>
<rsweb:ReportViewer ID="DReportViewer" runat="server">
</rsweb:ReportViewer>
</div>
</form>
But when I run the page, It gives an error stating
A data source instance has not been supplied for the data source
'Login_Login'.
Please help me out ASAP....
This means that a Datasource on your report called "Login_Login" has not been set to an instance.'
Do you have only one Datasource on your Report? If so try to change the name of your ReportDataSource to "Login_Login" like this
ReportDataSource rds1 = new ReportDataSource("Login_Login", dt);
The name you give the instance has to match the name of the datasource you have defined in the report
If you have multiple Datasources in your report, please add instances to all of them. Like I do in this example
LocalReport report = new LocalReport();
report.DataSources.Add(new ReportDataSource("Login_Login", (DataTable)ds.LoginTable));
report.DataSources.Add(new ReportDataSource("Report_Login", (DataTable)ds.ReportLoginTable));
report.DataSources.Add(new ReportDataSource("Report_Another_One", (DataTable)ds.AnotherTable));

Getting Row's Name in a DataList

I have a datalist and would like to pull the row names from the table that I am getting my values from for the datalist. Heres an example of what I would like to do.
<HeaderTemplate>
'Get data row names
'Maybe something like Container.DataItem(row)?
</HeaderTemplate>
If you are using a DataTable as a Data Source for your Data List you could use the OnItemCreated method and provide a custom handler for the ItemCreated event to add the column header values. I'm not sure why you would want to do this. It sounds like a Repeater or GridView might be better suited to your needs. At any rate, here's the code.
<asp:DataList ID="DataList1" runat="server" OnItemCreated="DataList1_ItemCreated"
ShowHeader="true" >
<HeaderTemplate>
</HeaderTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT [id], [name], [email], [street], [city] FROM [employee_tbl]", conn);
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
foreach (DataColumn col in dt.Columns)
{
Literal lit = new Literal();
lit.Text = col.ColumnName;
e.Item.Controls.Add(lit);
}
}
}
You could do the following, but I doubt it would work. I don't believe DataItems are available at the point when the Header is being created.
((DataRowView)Container.DataItem).DataView.Table.Columns
If this works, you can loop through this collection and inspect each item's ColumnName property.
A better idea would be to either:
Create a property in codebehind that returns a List<string> of appropriate column headers. You can refer to this property in markup when you're declaring the header.
Add a handler for the ItemDataBound event and trap header creation. You will still need a way to refer to the data elements, which probably haven't been prepped at this point.

Resources