I'm trying to display multiple rows from a query into a literal in asp.net c#. Here is my code for doing so:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[dbo].[GetUsersLeagues]", conn);
cmd.CommandType = CommandType.StoredProcedure;
string userId = Membership.GetUser().ProviderUserKey.ToString();
SqlParameter userIDParam = new SqlParameter("#userId", userId);
cmd.Parameters.Add(userIDParam);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dReader.Read())
{
usersLeagues.Text = (dReader["LeagueName"].ToString());
}
dReader.Close();
conn.Close();
}
My issue is that the literal is only displaying one of the rows, i've tried this with a list box and all rows were displayed.
Any suggestions?
Thanks in advance!
You are replacing the value of the Text property on each iteration:
while (dReader.Read())
{
usersLeagues.Text = (dReader["LeagueName"].ToString());
}
Instead of that, you need to concatenate the values on each iteration:
while (dReader.Read())
{
usersLeagues.Text += (dReader["LeagueName"].ToString()) + Environment.NewLine;
}
In the above example, using += causes an append to the current value of usersLeagues.Text, instead of a replacement.
Related
I have a DropDownList that gets populated by a SQL Server table called tblVisa. My issue is that the values that are being populated from the SQL Server table are not being saved. Everything else gets saved except for my DropDownLists. I've tried using .SelectedValue and .Text, but it still does not work.
Here is my code
protected void PopulateVisaType()
{
List<ListItem> result = new List<ListItem> { new ListItem("", "") };
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "SELECT VisaType FROM tblVisa ORDER BY VisaType ASC" };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
result.Add(new ListItem(read["VisaType"].ToString(), read["VisaType"].ToString()));
}
read.Close();
sqlConn.Close();
cmd.Dispose();
DDLVisa.DataSource = result;
DDLVisa.DataValueField = "value";
DDLVisa.DataTextField = "text";
DDLVisa.DataBind();
}
Here's my code for saving the information into the database:
protected void LbSaveProfile_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "spSaveNewProviderInformation", CommandType = CommandType.StoredProcedure };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
cmd.Parameters.AddWithValue("#EmployeeNumber", TbEmployeeNumber.Text.Trim());
cmd.Parameters.AddWithValue("#SSN", TbSSN.Text.Trim());
cmd.Parameters.AddWithValue("#ContractType", DDLContractType.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Firstname", TbFirstname.Text.Trim());
cmd.Parameters.AddWithValue("#Lastname", TbLastname.Text.Trim());
cmd.Parameters.AddWithValue("#MiddleInitial", TbMiddleInitial.Text.Trim());
cmd.Parameters.AddWithValue("#ContractRenewalDate", TbContractRenewalDate.Text.Trim());
cmd.Parameters.AddWithValue("#Position", DDLPosition.Text.Trim());
cmd.Parameters.AddWithValue("#Specialty", DDLSpecialty.Text.Trim());
cmd.Parameters.AddWithValue("#PrimaryDepartment", DDLPrimaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#SecondaryDepartment", DDLSecondaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#Gender", DDLGender.Text.Trim());
cmd.Parameters.AddWithValue("#Birthdate", TbBirthdate.Text.Trim());
cmd.Parameters.AddWithValue("#EmailAddress", TbEmailAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PhoneNumber", TbPhoneNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Address", TbAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PassportNumber", TbPassportNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Citizenship", DDLCitizenship.Text.Trim());
cmd.Parameters.AddWithValue("#Visa", DDLVisa.Text.Trim());
cmd.Parameters.AddWithValue("#Status", 1);
cmd.ExecuteNonQuery();
sqlConn.Close();
Alert("Provider Information saved!");
ClearControls();
}
You much better to provide the drop down list with column names.
So, say this:
protected void PopulateVisaType()
{
SqlConnection sqlConn = new SqlConnection("");
using (SqlCommand cmd = new SqlCommand("SELECT VisaType FROM tblVisa ORDER BY VisaType ASC", sqlConn))
{
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
DDLVisa.DataSource = cmd.ExecuteReader();
DDLVisa.DataValueField = "VisaType";
DDLVisa.DataTextField = "VisaType";
DDLVisa.DataBind();
//DDLVisa.Items.Insert(0, new ListItem("")); // optional blank row choice
sqlConn.Close();
}
}
So the TextField, and the DataText field need to be a named column from the data source.
I also included an optional first blank option if you need/want/expect to have no choice.
However, keep in mind that this empty string should be translated into a null in your database if you don't allow (or want) empty strings, and want a null for that value. This applies to all of your values. (perhaps the stored procedure does this?).
I have two stored procedures:
spRO_Status_OrderInfo
spRO_Status_Change
Each procedure returns a different table. I have only one user input parameter TN. This parameter I'm reading from search txt line (inputTNReturn.Value)
Each procedure posts data in a different grid view
spRO_Status_OrderInfo -->> gvSearchResults
spRO_Status_Change -->> GridView1
This code returns only LAST stored procedure to last gridView
spRO_Status_Change -->> GridView1
I don't have any idea where is my mistake and why I can get 2 grid view from 2 procedure.
I'll appreciate for any help
protected void btnSearch_Click(object sender, EventArgs e)
{
string connectionStr = ConfigurationManager
.ConnectionStrings["ConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionStr))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "[spRO_Status_OrderInfo]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spRO_Status_Change";
cmd.CommandType = CommandType.StoredProcedure;
if (inputTNReturn.Value.Trim() != "")
{
SqlParameter param = new SqlParameter("#TN", inputTNReturn.Value);
cmd.Parameters.Add(param);
SqlDataReader rdr = cmd.ExecuteReader();
gvSearchResults.DataSource = rdr;
gvSearchResults.DataBind();
GridView1.DataSource = rdr;
GridView1.DataBind();
lblinputTNReturn.Text = inputTNReturn.Value;
}
}
if (inputTNReturn.Value == "")
{
inputTNReturn.Value = "Please add tracking number";
}
con.Close();
}
}
Here is where you're setting the first stored procedure
cmd.CommandText = "[spRO_Status_OrderInfo]";
cmd.CommandType = CommandType.StoredProcedure;
Here is where you're overwriting the above
cmd.CommandText = "spRO_Status_Change";
cmd.CommandType = CommandType.StoredProcedure;
You're not adding a second command text / type, you're just over writing the first one which is why you're only seeing the second one come out in the output.
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();
}
}
}
Hey everyone pretty new to SQL Database functions but have been coding in c# for about a year now still not that great at it but I'm getting there!
I'm currently creating a football application and to Edit players and Matches i was wanting to use one drop down combo box to retrieve data from an SQL database which then would populate other text boxes and combo boxes. I've had a go at it myself but don't know where i'm going wrong.
On form load my connection opens i populate my datasets and i execute this method to populate my combobox
private void Navigate()
{
string showPlayers = "SELECT * From Add_Players";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayer.Items.Add(myReader[0]);
}
conn.Close();
}
After which in the combo box selected index changed method i have this code
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
string showPlayers = "SELECT * From Add_Players WHERE Player_ID ='"
+ comboEditPlayer + "' ;";
SqlCommand cmdData = new SqlCommand(showPlayers, conn);
SqlDataReader myReader = cmdData.ExecuteReader();
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
conn.Close();
conn.Dispose();
}
catch (Exception comboFail)
{
MessageBox.Show(comboFail.ToString());
}
}
I've been told this code is open and i need to use parameterized queries for preventing hacker attempts which i have started but do not know what Parameter i should be adding to the code i have for this is below
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID ="
+ comboEditPlayer.SelectedValue + "", connection))
{
command.Parameters.Add(new SqlParameter ("",));
}
}
}
All help is appreciated and please go easy on me :P
You could add a parameter to the collection with the value of your ComboBox, then execute the query and read back the values from the reader
private void comboEditPlayer_SelectedIndexChanged(object sender, EventArgs e)
{
string connectionString =
ZimbFootball.Properties.Settings.Default.Football2ConnectionString;
using (SqlConnection connection = new SqlConnection (connectionString))
using (SqlCommand command = new SqlCommand(
"SELECT * From Add_Players WHERE Player_ID =#id", connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", comboEditPlayer.Text);
using(SqlDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
comboEditPlayerPos.Items.Add(myReader[1]);
txtEditPlayerName.Text = myReader[2].ToString();
txtEditPlayerSecond.Text = myReader[3].ToString();
comboEditPlayerStatus.Items.Add(myReader[4]);
}
}
}
}
I Have a gridview with just one column. I have written code like
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string Users = GridView1.Rows[i].Cells[0].Text;
string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
" values(#FileName, #DateTimeUploaded, #Type, #Username)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", datalink);
cmd.Parameters.AddWithValue("#Type", ext);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
cmd.Parameters.AddWithValue("#Username", Users);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
con.Close();
con.Dispose();
}
If this gridview has 2 rows, then the first row is stored in database twice. If gridview has 3 rows then the first row is stored thrice. How can I solve this?
Explanation:
You are inserting your data into the database inside your GridView's RowDataBound event - this is executing every time a DataRow is being bound! This, along with the fact that you're looping accross every row each time using:
for (int i = 0; i < GridView1.Rows.Count; i++) { // inserting record from each row }
means your rows are going to be inserted more than once as more rows are bound. You need to remove your for loop, and use e.Row.Cells[0] instead to reference and insert just the currently bound row data.
string Users = e.Row.Cells[0].Text;
You probably also want to check for only DataRows so your operations don't occur on footer/header rows etc.
New Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string Users = e.Row.Cells[0].Text; // current row being bound
string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
" values(#FileName, #DateTimeUploaded, #Type, #Username)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", datalink);
cmd.Parameters.AddWithValue("#Type", ext);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
cmd.Parameters.AddWithValue("#Username", Users);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
}
}