How to populate the excelsheetcloumn names into a dropdown list? - asp.net

Hi i have an excel sheet with headers,i want to populate those headers into a dropdown list...
can any one help me with the select statement and procedure
i am working on a code i dnt know whether its correct or not
DropDownList list = new DropDownList();
string connectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Excelpath);
string query1 = String.Format("select * from [{0}]", DDlist.SelectedItem.Text);
// OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query1, connectionstring);
using (OleDbConnection conn1 = new OleDbConnection(connectionstring))
{
OleDbCommand odc1 = new OleDbCommand(string.Format(query1, conn1));
conn1.Open();
OleDbDataReader dr;
dr = odc1.ExecuteReader();
while (dr.Read())
{
list.Items.Add(dr[column.ColumnName].ToString());
}
dr.Close();
conn1.Close();
}
in this method i am geting an error at this line
dr = odc1.ExecuteReader();Error:ExecuteReader: Connection property has not been initialized.
can any one help mw with this, thanks in advance

try this it may work.....
foreach (DataTable table in DS.Tables)
{
foreach (DataColumn column in table.Columns)
{
DropDownList list = new DropDownList();
string connectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Excelpath);
string query1 = String.Format("select * from [{0}]", DDlist.SelectedItem.Text);
using (OleDbConnection conn1 = new OleDbConnection(connectionstring))
{
OleDbCommand odc1 = new OleDbCommand(query1, conn1);
conn1.Open();
DataTable dte = null;
DataSet ds = new DataSet();
dte = conn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = odc1;
objAdapter1.Fill(ds, "xldata");
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
list.Items.Add(ds.Tables[0].Columns[i].ColumnName.ToString());
}
conn1.Close();
}

I think you are not passing Connection to OleDBCommand. So try,
OleDbCommand odc1 = new OleDbCommand(query1, conn1);

The OleDbCommand class has two main parameters to be passed for a proper execution. That are Query and connection object. In your code you are passing the connection, but it is placed inside the String.Format(), so place it outside. See the code below....
OleDbCommand odc1 = new OleDbCommand(string.Format(query1, conn1));
TO
OleDbCommand odc1 = new OleDbCommand(query1, conn1);

Related

Unable to do search for selected items

I am using this code to search for selected items inside a checkbox list and it doesn't work.
protected void btnSearchCode_Click(object sender, ImageClickEventArgs e)
{
string selectedValues = string.Empty;
foreach (ListItem item in cblCode.Items)
{
if (item.Selected)
selectedValues += item.Value + ",";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
cblCode.DataSource = DataReport.SearchCode(selectedValues);
cblCode.DataBind();
}
public static DataTable SearchCode(string selectedValues)
{
string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
DataTable datatable = new DataTable();
using (SqlConnection conn = new SqlConnection(strcon))
{
conn.Open();
SqlCommand command = new SqlCommand();
string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")", conn;
command.Connection = conn;
SqlDataAdapter dataadapter = new SqlDataAdapter();
dataadapter.SelectCommand = command;
DataSet ds = new DataSet();
dataadapter.Fill(datatable);
}
return datatable;
}
Really appreciate any help on this.
You have not used strQuery at all.
Try this :
public static DataTable SearchCode(string selectedValues)
{
string strcon = ConfigurationManager.ConnectionStrings["LocalDB"].ConnectionString;
DataTable datatable = new DataTable();
using (SqlConnection conn = new SqlConnection(strcon))
{
conn.Open();
string strQuery = "Select Group, Name from Details where Code in (" + selectedValues + ")";
SqlCommand command = new SqlCommand(strQuery, conn);
SqlDataAdapter dataadapter = new SqlDataAdapter();
dataadapter.SelectCommand = command;
DataSet ds = new DataSet();
dataadapter.Fill(datatable);
}
return datatable;
}
You create the query string but you never assign it to the command variable. Therefore, when you assign it to selectCommand, there isn't anything to query from DB. You want to add this line of code to assign the query string to variable:
command = new SqlCommand(strQuery,conn);
Always Use SqlParamerter while passing parameters to the database
i think You are missing single inverted comma because Your SeletedValues is string
string strQuery = "Select Group, Name from Details
where Code in ('" + selectedValues + "')", conn;

Join/merge two excel files in asp.net and display them in gridview

I am trying to merge two excel files in asp.net and display them in gridview as one table. The code below is displaying only one table. Can anyone tell me what is the problem with the code below? If you have a better idea please let me know.
protected void MergTables()
{
string connString = ConfigurationManager.ConnectionStrings[hwTypes].ConnectionString;
OleDbConnection DBConnection = new OleDbConnection(connString);
DBConnection.Open();
OleDbCommand DBCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", DBConnection);
OleDbDataAdapter da = new OleDbDataAdapter(DBCommand);
DataSet ds = new DataSet("Stock");
da.Fill(ds, "HWTypes");
DBConnection.Close();
string _stockConn = ConfigurationManager.ConnectionStrings[stockConn].ConnectionString;
DBConnection = new OleDbConnection(_stockConn);
DBConnection.Open();
DBCommand = new OleDbCommand("SELECT * FROM [Stock_voorlopig$]", DBConnection);
da = new OleDbDataAdapter(DBCommand);
da.Fill(ds, "Stock");
DBConnection.Close();
for (int i = 0; i < ds.Tables["HWTypes"].Rows.Count; i++)
{
ds.Tables["HWTypes"].Rows[i]["ProductID"] = ds.Tables["Stock"].Rows[i]["Partno"];
}
GridView1.DataSource = ds.Tables["Stock"];
GridView1.DataBind();
}
The problem is that you are using just a single DataTable in your GridView and you haven't yet joined both.
Here's an approach which uses Linq-To-DataSet to join both tables and creates an anonymous type as datasource for the GridView.
DataSet ds = new DataSet("Stock");
using (var dbConnection = new OleDbConnection(connString))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "HWTypes");
}
using (var dbConnection = new OleDbConnection(stockConn))
using (var dbCommand = new OleDbCommand("SELECT * FROM [Stock_voorlopig$]", dbConnection))
using (var da = new OleDbDataAdapter(dbCommand))
{
da.Fill(ds, "Stock");
}
var joined = from rType in ds.Tables["HWTypes"].AsEnumerable()
join rStock in ds.Tables["Stock"].AsEnumerable()
on rType.Field<string>("ProductID") equals rStock.Field<string>("Partno")
select new
{
ProductID = rType.Field<string>("ProductID")
// add the other columns you need here
};
GridView1.DataSource = joined;
GridView1.DataBind();

Detailsview in ASP.NET

I am trying to hit sql server with objectdatasource and return a datatable to fill my details view control. the selected ID value is returned by a gridview control. It seems like the datatable is not filled by adapter, and i couldn't figure out why. The ID in sql is set as a primary key (Int, 4, not null). The debugger says the Detail datatable is null. Any help is much appreciated.
public DataTable GetDetail(string ID)
{
if (ID == "")
{
return null;
}
else
{
DataTable Detail = null;
using (SqlConnection conn = new SqlConnection(connection))
{
string comm = #"select * from dbo.Products where ID = #ID";
conn.Open();
SqlDataAdapter adapter=null;
using (SqlCommand cmd = new SqlCommand(comm, conn))
{
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = Convert.ToInt32(ID);
adapter = new SqlDataAdapter(cmd);
adapter.Fill(Detail);
return Detail;
}
}
}
I think you missed the commandType
cmd.CommandType = CommandType.Text;
Try this
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(connection))
{
string myquery="select * from dbo.Products where ID = #ID";
SqlCommand cmd = new SqlCommand(myquery, con);
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = cmd;
cmd.Parameters.Add("#ID", SqlDbType.NVarChar, 15).Value = ID;
dap.Fill(ds);
return ds.Tables[0];
}
Thanks for ALL.
The problem is I didnt initialize my datatable to a new instance.
DataTable Detail = null; ===> DataTable Detail = new Datatable();
and also the convert should be done in sql not in codes.
cmd.Parameters.Add("ID", System.Data.SqlDbType.Int, 4).Value = ID;
string comm = #"select * from dbo.Products where ID = convert(int,#ID)";

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

how to write select parameterized query in asp.net

Below code is written to call parameterized select query in asp.net
public bool checkConflictTime()
{
bool TimeExists = false;
DataSet ds = new DataSet();
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = ConfigurationManager.ConnectionStrings["TestConn"].ConnectionString;
string sql = #"SELECT * FROM Images WHERE starttime= #starttime AND endtime = #endtime";
SqlCommand sqlcommand = new SqlCommand(sql,sqlconn);
//sqlcommand.Connection = sqlconn;
//string sql = "CheckConflictTimings";
sqlcommand.CommandType = CommandType.Text;
sqlcommand.CommandText = sql;
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));
sqlcommand.Parameters.Add(new SqlParameter("#endtime", ddlEndTime.SelectedItem.Text));
SqlDataAdapter da = new SqlDataAdapter(sql, sqlconn);
try
{
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
TimeExists = true;
}
}
catch (Exception ex)
{
}
finally
{
sqlconn.Close();
sqlconn.Dispose();
}
return TimeExists;
}
Is there something wrong? it threw error of :Must declare the scalar variable "#starttime"
when filling data adapter.
Try
SqlDataAdapter da = new SqlDataAdapter(sqlcommand);
Try
sqlcommand.Parameters.Add(new SqlParameter("starttime", ddlStartTime.SelectedItem.Text));
I don't think you need the # prefix when adding the parameter.
I think you're not passing your command as a SelectCommand to the adapter.
da.SelectCommand = sqlcommand;
Try
sqlcommand.Parameters.AddWithValue("#starttime",ddlStartTime.SelectedItem.Text);
instead of
sqlcommand.Parameters.Add(new SqlParameter("#starttime", ddlStartTime.SelectedItem.Text));

Resources