get simple drop down value in webmethod - c#

below is my code in which in want to use dropdownlist but i am unable to call its id: error showing that object require for static method.
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["mycon"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tbl_group where Group_Name=" + drpgovtypelcns1.Selecteditem.Text, con);
cmd.Parameters.AddWithValue("#Group_Name", prefixText);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][1].ToString());
}
return CityNames;
}

Related

C# Paginate SQL result from a proc call

I have the following method that calls a proc in my database and returns the results into a dataset. The dataset is then used to populate a table I render using MVC & cshtml.
The method is:
public DataSet CallProcToDataSet(string procName)
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
}
}
}
return ds;
}
This works fine, however what I want is to have some way of paginating the results so that only 10 at a time are displayed. What is the best way for me to achieve this that doesn't involve any changes to the proc calls?
You can use this overload of the Fill method
public int Fill(int startRecord, int maxRecords, params DataTable[] dataTables);
(link: https://msdn.microsoft.com/en-us/library/0z5wy74x(v=vs.110).aspx)
This way you will only return a subset of the records without modifying your stored procedure.
Example (MSTest)
[TestMethod]
public void TestMethod1()
{
DataSet ds = new DataSet();
var procName = "sp_server_info";
string constr = ConfigurationManager.ConnectionStrings["UAT"].ConnectionString;
var tblName = "result";
var tbls = new[] { ds.Tables.Add(tblName) };
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(procName))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(0, 10, tbls);
}
}
}
Assert.AreEqual(tbls[0].Rows.Count, 10);
}
Try following :
DataSet ds = new DataSet();
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i += 10)
{
DataTable pageTable = dt.AsEnumerable().Where((x, n) => (n >= i) && (n < i + 10)).CopyToDataTable();
}

Issue with List.Add(): it only displays the last row

Issue with List.Add(): it only saves the last added item, it binds the last data repeatedly, please someone help me to clear it. I am trying out in mvc 4 as Begineer. I am also struggling with basic of mvc 4. thank u in advance.
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=#batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var model = new MyCourseData();
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
This happens because you are adding the same instance of MyCourseData in the list with value changing in every iteration.
You need to create new instance of MyCourseData for every iteration,
var modelList = new List<MyCourseData>();
string batchid = System.Web.HttpContext.Current.Request.QueryString["batchid"];
SqlConnection con = null;
string result = "";
DataSet ds = null;
con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd = new SqlCommand("select * from [Student].[dbo].[tbl_batch] where batchid=#batchid", con);
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#batchid", batchid);
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds);
con.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
var classdates = ds.Tables[0].Rows[i]["class_dates"].ToString();
int j = 0;
// string[] parts = classdates.Split(',');
foreach (string CourseDates in classdates.Split(','))
{
var model = new MyCourseData();
model.batchid = ds.Tables[0].Rows[i]["batchid"].ToString();
model.course = ds.Tables[0].Rows[i]["course"].ToString();
model.trainer = ds.Tables[0].Rows[i]["trainer"].ToString();
model.class_dates = CourseDates;
modelList.Add(model);
}
}
return modelList;
}

Ajax Autocomplete Extender Not Working For Number Auto completion

My ASPX Code:
<asp:TextBox ID="txtCollectionCode" runat="server" CssClass="txt" />
<asp:AutoCompleteExtender ID="AutoCompleteCollectionCode" runat="server" TargetControlID="txtCollectionCode" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="100" ServiceMethod="GetCollectionCode" />
Code Behind:
public static List<string>GetCollectionCode(string prefixText)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("Select Collection_Code From Collections_New WHERE Collection_Code LIKE #Collection_Code+'%'", conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
conn.Close();
List<string> CollectionCodes = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CollectionCodes.Add(dt.Rows[i][1].ToString());
}
return CollectionCodes;
}
My Problem: This code works when I have to draw names. But from the same table when I try to draw the collection_codes (3001,3002,3003 for example) there is no autosuggestion.
Any help would be greatly appreciated! Thank you
I guess I figured it out.
public static ListGetCollectionCode(string prefixText)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("Select * FROM Collections_New WHERE Collection_Code LIKE '" + prefixText + "%'", conn);
DataSet ds = new DataSet();
SqlDataAdapter dta = new SqlDataAdapter(cmd);
dta.Fill(ds);
conn.Close();
List<string> CollectionCodes = new List<string>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CollectionCodes.Add(ds.Tables[0].Rows[i]["Collection_Code"].ToString());
}
return CollectionCodes;
}

DataRow Is Not Showing Up

I have used DataRow which could be displayed in a combobox in my WinForm but somehow, it is not working, although the entire table is successfully being displayed in the gridview.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
con.ConnectionString = "Data Source=.;Initial Catalog=StudentDetails;Integrated Security=True";
cmd.Connection = con;
cmd.CommandText = "select * from StuDet";
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dr[0]);
}
}
You create an empty new row
DataRow dr = dt.NewRow();
and add it Rows.Count times to comboBox1. I think what you want is to go through each row in dt.Rows:
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Roll"]);
}
Just now figured out the answer, Please take a look at the loop at the bottom.
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
con.ConnectionString = "Data Source=.;Initial Catalog=StudentDetails;Integrated Security=True";
cmd.Connection = con;
cmd.CommandText = "select * from studet";
da.SelectCommand = cmd;
da.Fill(ds);
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
////////////////////////////////////////////////////
DataRow dr = dt.NewRow();
for (int i = 0; i < dt.Rows.Count; i++)
{
dr[0] = dt.Rows[i][0];
comboBox1.Items.Add(dr[0]);
}
}

How to get data from SQL database to store in combo box - C#

How can i get the value of company_name from Comp table and store it on a comboBox?
here is my initial code on getting the values from Database and store it on a combobox:
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
it point out to da.fill(ds) and says "Could not locate entry in sysdatabases for database 'select company_name from JO'. No entry found with that name. Make sure that the name is entered correctly."
hope for your reply thanks!
Use datareader it is much simpler \
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand(Sql, conn);
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
combobox1.Items.Add(DR[0]);
}
If you set up your connection string to be something of this sort:
string SqlConnectionString = "Data Source=[SERVER];Initial Catalog=[DATABASE];"
Then using that set up, you can set your string 'Sql' as:
string Sql = "select company_name from dbo.Comp";
This could be a possible set up you could use to read out the values.
using (SqlConnection saConn = new SqlConnection(this.ConnectionString))
{
saConn.Open();
string query = "select DBName from dbo.Company";
SqlCommand cmd = new SqlCommand(query, saConn);
using (SqlDataReader saReader = cmd.ExecuteReader())
{
while (saReader.Read())
{
string name = saReader.GetString(0);
combobox1.Add(name);
}
}
saConn.Close();
}
I would like to introduce you a very simple way to SQL data into a combobox as:
first you have a create a SQL table,
in C# platform drop a combobox and go to its property,
in the property menu click on "DataSource"
specify the database and table to load into combobox,
Note, the combobox name and table's row should be the same.
{
SqlConnection con =new SqlConnection("Data Source=Server_Name;Initial Catalog=Database_Name;integrated security=true");
SqlCommand cmd;
SqlDataReader dr;
private void CashMemoForm_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("Select Column_Name From Table_Name", con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr[0]).ToString();
}
}
}
Have you ever tried Entity Framework for database access and dto creation?
Change your line to cmd.CommandType = CommandType.Text; instead of cmd.CommandType = CommandType.StoredProcedure;
Try this
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("--Select--", "0"));
}
There is no use of for loop. you just need to check that whether the dataset contains rows or not.
string Sql = "select Company_ID,company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
comboBox1.DataSource = ds.Tables[0];
comboBox1.DataTextField = "company_name";
comboBox1.DataValueField = "Company_ID";
comboBox1.DataBind();
comboBox1.Items.Insert(0, new ListItem("Select", "0"));
}
string Sql = "select company_name from JO.dbo.Comp";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
comboBox1.Items.Add(ds.Tables[0].Rows[i][0].ToString());
public System.Data.DataTable EmployeeViewAll()
{
DataTable dtbl = new DataTable();
try
{
// Here it shuld be your database Connection String
string connectionString = "Server = .; database = HKS; Integrated Security = true";
using (SqlConnection sqlCon = new System.Data.SqlClient.SqlConnection(connectionString))
{
SqlDataAdapter SqlDa = new SqlDataAdapter("employeeViewAll", sqlCon);
SqlDa.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlDa.Fill(dtbl);
}
return dtbl;
}
catch (Exception)
{
throw;
}
}
public void ComboFill()
{
DataTable dt = new DataTable();
eSP SP = new eSP();
d = SP.EmployeeViewAll();
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "department";
comboBox1.ValueMember = "empName";
}

Categories

Resources