Detailsview in ASP.NET - 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)";

Related

asp.net - Please show me a example of find method of dataview control

I am trying to find in DataView but can't.
please show me alternative if any..
string conString = System.Configuration.ConfigurationManager.ConnectionStrings["aspDB"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(cmdText:"select * from name",
connection: con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet("Customers");
adapter.Fill(ds,"Customers");
DataView dv;
dv= new DataView(ds.Tables[0],"","id desc", DataViewRowState.CurrentRows);
var find = dv.Find("abc");
if (find == -1)
{
Response.Write("<script>alert('No Match')</script>");
}
else
{
Response.Write("<script>alert('Match Found')</script>");
}

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;

How can I use DataTextField on an element that is not a ListControl?

So here's my situation: I have a DropDownList that I populate when a certain event is triggered. To populate it, I execute a SQL query that returns two columns: ID and Name. I bind the Name to the DropDownList using DataSource/DataTextField/DataValueField, but I want to save the ID as well (to use in a second query). How can I do this?
I have tried saving the ID to a hidden input field, because I want to use it but not display it to the user. But input is not a ListControl, so it doesn't work. How do I get the matching ID of the Name selected in the DropDownList?
string strConn = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Id, Name FROM Users WHERE Age > 10";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
NameDropDown.DataSource = objDs.Tables[0];
NameDropDown.DataTextField = "Name";
NameDropDown.DataValueField = "Name";
NameDropDown.DataBind();
NameDropDown.Items.Insert(0, "--Select--");
}
else
{
NameDropDown.Items.Clear();
NameDropDown.Items.Insert(0, "No names found");
}
Consider:
if (objDs.Tables[0].Rows.Count > 0)
{
NameDropDown.DataSource = objDs.Tables[0];
NameDropDown.DataTextField = "Name";
NameDropDown.DataValueField = "ID"; /*why wouldn't this be ID*/
NameDropDown.DataBind();
NameDropDown.Items.Insert(0, "--Select--");

How to populate the excelsheetcloumn names into a dropdown list?

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);

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