I'm new to c#, as in.
I'm currently working on a search function in c# using 3 DropDownLists and a submit button. When a user select an item on DropDownList and click submit, it will print the table for the respective selection.
There are 3 DropDownLists:
a province,
city,
specialization.
This will search the available doctors that suits the selection. For example I choose province1 on 1st DropDownList, city1 on the 2nd and a psychologist on 3rd, when the submit button is fired, it will print the available doctors that is in province1, city1 and has a specialization of psychologist.
I already have a code, still figuring it out but, when i click the submit button, nothing is happening. Can someone help me?
Here's what I've done so far:
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
if (!IsPostBack)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_province ORDER BY PROVINCE_NAME ASC", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
ddlProvince.DataSource = dt;
ddlProvince.DataTextField = "PROVINCE_NAME";
ddlProvince.DataValueField = "PROVINCE_CODE";
ddlProvince.DataBind();
ddlProvince.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
}
protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_province");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_city WHERE PROVINCE_CODE =#pcode", conn);
comm.Parameters.AddWithValue("#pcode", ddlProvince.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#pcode";
param.Value = ddlProvince;
comm.Parameters.Add(param);
}
ddlCity.DataSource = dt;
ddlCity.DataTextField = "CITY_NAME";
ddlCity.DataValueField = "CITY_CODE";
ddlCity.DataBind();
ddlCity.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_city");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM emed_specialization", conn);
comm.Parameters.AddWithValue("#ccode", ddlCity.SelectedValue);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
SqlParameter param = new SqlParameter();
param.ParameterName = "#ccode";
param.Value = ddlCity;
comm.Parameters.Add(param);
}
ddlSpec.DataSource = dt;
ddlSpec.DataTextField = "SPEC_NAME";
ddlSpec.DataValueField = "SPEC_CODE";
ddlSpec.DataBind();
ddlSpec.Items.Insert(0, new ListItem("---------------SELECT---------------", "0"));
}
protected void btnSub_Click(object sender, EventArgs e)
{
string constring = ConfigurationManager.ConnectionStrings["AccreString"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
DataTable dt = new DataTable("emed_doctors");
using (conn)
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where Province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
SqlDataAdapter adptr = new SqlDataAdapter(comm);
adptr.Fill(dt);
}
}
}
Make change in this line of code which is in submit button click function
Correct code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where province = '" + ddlProvince.SelectedItem.ToString() + "'", conn);
because as you see your code query is incorrent have look to your code which is incorrect
Wrong code:
SqlCommand comm = new SqlCommand("SELECT DOCTOR_NAME FROM emed_doctors where (" + ddlProvince.SelectedItem.ToString() + " ", conn);
Edit:
if you want to display record that you got in DataTable you either need loop through the records or you need to use GridView for that...i think you miss that thing
in above one after where clause you miss the name of the filed you need to made filter on... i have written update code by modifying that condition.
See MSDN for GridView.
You said that after clicking submit, nothing happend. But in btnSub_Click I didn't see anything that displaying the result or changing anything on the page. You should bind dt to some control like a gridview etc.
Related
So I am trying to populate one dropdown from the selection of another. I have tested the stored proc I am using and, when entering a value, I get the right results. I know there are many questions like this but none seem to fix my issue.
protected void Page_Load(object sender, EventArgs e)
{
DataTable environments = new DataTable();
var connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Environment FROM Environments", conn);
adapter.Fill(environments);
ddlEnvironment.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddlEnvironment.SelectedIndex = 0;
ddlEnvironment.DataSource = environments;
ddlEnvironment.DataTextField = "Environment";
ddlEnvironment.DataValueField = "Environment";
ddlEnvironment.DataBind();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adapter2 = new SqlDataAdapter();
DataTable servers = new DataTable();
cmd = new SqlCommand("sp_EnvironmentSelection", conn);
cmd.Parameters.AddWithValue("#Environment", ddlEnvironment.SelectedValue);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
adapter2.SelectCommand = cmd;
adapter2.Fill(servers);
ddlServer.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddlServer.SelectedIndex = 0;
ddlServer.DataSource = servers;
ddlServer.DataTextField = "ServerName";
ddlServer.DataValueField = "ServerIP";
ddlServer.DataBind();
}
}
The issue is, I don't get any choices on the second drop down no matter my selection on the first drop down.
Here is the stored proc if needed.
#Environment nvarchar(50)
AS
BEGIN
SET NOCOUNT ON
SELECT Server.ServerName, Server.ServerIP, Environments.Environment
FROM Server
INNER JOIN Environments
ON
Environments.Environment=Server.Environment
WHERE Server.Environment=#Environment
END
If you step through your code as it is executing, you will see that when cmd.Parameters.AddWithValue("#Environment", ddlEnvironment.SelectedValue); is called, ddlEnvironment.SelectedValue will not be set to anything. This is because at the time you're running this code, it's right after ddlEnvironment is being binded to its data. It has no information at that time about what the user selected.
You need to move your binding of the second list into an event handler that handles the ddlEvironment.SelectedIndexChanged event. In there, ddlEnvironment.SelectedValue will be set to what the user selected. And in Page_Load, you do not want to re-bind the first list each time there is a postback, so it needs to be wrapped in an if (!Page.IsPostBack).
See the question here: DropDownList's SelectedIndexChanged event not firing
Your first dropdown list in the asp code needs to look something like this:
<asp:DropDownList ID="ddlEnvironemnt" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlEnvironemnt_SelectedIndexChanged">
</asp:DropDownList>
Your page_load would be like this:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
return;
}
DataTable environments = new DataTable();
var connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Environment FROM Environments", conn);
adapter.Fill(environments);
ddlEnvironment.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddlEnvironment.SelectedIndex = 0;
ddlEnvironment.DataSource = environments;
ddlEnvironment.DataTextField = "Environment";
ddlEnvironment.DataValueField = "Environment";
ddlEnvironment.DataBind();
}
}
And you would have an event handler:
protected void ddlEnvironemnt_SelectedIndexChanged(object sender, EventArgs e)
{
var connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adapter2 = new SqlDataAdapter();
DataTable servers = new DataTable();
cmd = new SqlCommand("sp_EnvironmentSelection", conn);
cmd.Parameters.AddWithValue("#Environment", ddlEnvironment.SelectedValue);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
adapter2.SelectCommand = cmd;
adapter2.Fill(servers);
ddlServer.Items.Insert(0, new ListItem(String.Empty, String.Empty));
ddlServer.SelectedIndex = 0;
ddlServer.DataSource = servers;
ddlServer.DataTextField = "ServerName";
ddlServer.DataValueField = "ServerIP";
ddlServer.DataBind();
}
}
Hope You all Are Fine
Can any one help me kindly i have a grid view that fetch tha record from database but show all the previous data which i entered by the grid but now i want to show the all data which i entering till the pageload even called, when page load that should not show all the entered records.
Thanks in Advance
Here is my code behind work
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.65;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=mushko");
using (connection)
{
// SqlCommand theCommand = new SqlCommand("select distinct T1.SlpCode,T1.SlpName,T3.StepId,T3.Descript from OSLP T1 left join OPR1 T2 on T1.SlpCode=T2.SlpCode right join OOST T3 on T3.StepId=t2.Step_Id ", connection);
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
If you want to keep the grid empty on page load event, then do not write the code to bind it on Page Load event, instead write the code on"Add Button" click event(if that's what you want).
For showing empty record Grid You can Use EmptyDataTemplate.
For more you can try this Link
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}
So here I'm trying to populate my dropdown list, the code behind is as below:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
con.Open();
SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
SqlDataReader ddlvalues = mycommand.ExecuteReader();
ddlTransactionCategory.DataSource = ddlvalues;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
mycommand.Connection.Close();
mycommand.Connection.Dispose();
}
the problem is, I can't seem to get it to work, any help? and is this code doing it right?
plz try below code:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection));
con.Open();
SqlCommand mycommand = new SqlCommand("select * from MSUnit", con);
SqlDataAdapter adp =new SqlDataAdapter(mycommand);
DataSet ds =new DataSet();
adp.Fill(ds);
ddlTransactionCategory.DataSource = ds;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
mycommand.Connection.Close();
mycommand.Connection.Dispose();
}
Thanks,
Hitesh
Can't bind to a SqlDataReader (or at least I've never tried it). Get a DataTable or a DataSet instead, fill it and then bind that to the dropdown the same way.
Use SqlDataAdataper like the one below
using (SqlConnection con = new SqlConnection(CommonFunctions.GetAppDBConnection(Constants.AppID, Constants.TMDDBConnection)))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from MSUnit", con);
DataTable dt = new DataTable
da.Fill(dt)
ddlTransactionCategory.DataSource = dt;
ddlTransactionCategory.DataTextField = "categoryCode";
ddlTransactionCategory.DataValueField = "OrgID";
ddlTransactionCategory.DataBind();
}
if you want to use DataReader you must insert one-by-one.
while (ddlvalues.Read())
{
ddlTransactionCategory.Items.Add(new ListItem(ddlvalues.getString("OrgID"),ddlvalues.getString("categoryCode")))
}