How to add data from textbox to database table - c#

I am a student and just start learning asp.net with C#.
I am using visual Studio 2015 and MSSQL Server 2012. I am facing a problem adding data in the database table from a webform.
I have established the connection successfully but couldn't be able to insert the data in the database table from a textbox.
I have search it at many places but couldn't able to do that.
So can anybody please tell me the simple and exact method to do that?

Kumar I am not sure if you facing issue in inserting any data into database or in capturing text from textbox and then inserting it into database.
However i will try to address both the issue.
for inserting into database you can visit Invalid column name sql error
as it has already been answered
now to capture the text froim textbox you can make use of HtmlElementClass
HtmlElement txtBox = null;
HtmlDocument doc = webBrowser1.Document;
if (doc != null)
{
txtBox = doc.GetElementByID("TxtboxelementId");
string txtValue=txtBox.InnerHtml
}

ASPX Page :
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
<asp:Button ID="btnInsert" runat="server" Text="Button" OnClick="btnInsert_Click" />
</div>
</form>
CS Code :
protected void Page_Load(object sender, EventArgs e)
{
}
private void InsertValue(string value)
{
using (SqlConnection con = new SqlConnection("YOUR_CONNECTION_STRING")) //Creating connection object
{
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO YOUR_TABLE_NAME (Field_Name) VALUES (#value)", con))
{
if (con.State == System.Data.ConnectionState.Closed) con.Open();
cmd.Parameters.AddWithValue("#value", value); // Adding parameter with value to command object
int result = cmd.ExecuteNonQuery(); // Executing query and it returns no of rows affected.
if (result > 0) Response.Write("Successful."); // Checking if no of rows affected is > 0 meaning value successfully inserted.
}
}
catch (SqlException ex) //Handling SQL Exceptions
{
this.LogErrors(ex);
}
}
}
private void LogErrors(Exception ex)
{
// Write error log logic here
}
protected void btnInsert_Click(object sender, EventArgs e) // insert data button click event handler
{
this.InsertValue(this.txtValue.Text);
}

SqlConnection con= (Connection Name)
If you are using without primary key in Database please go ahead with this
SqlCommand query = new SqlCommand("Insert into TABLE values ("+txtsample1.Text+")",con)
If it's with primary key mention your field names
SqlCommand query = new SqlCommand("Insert into TABLE (column1) values ("+txtsample1.Text+")",con)

Related

Getting cell value from GridView after Edit button is clicked Round 2

I posted this not long ago, but no I have to update the question to ensure I get the right answer.
I have a GridView. I need to update an SQL table based on values from the GridView.
When a user clicks the default EDIT button on the GridView, changes whatever they change, then hits UPDATE. Here is where I run into problems. I've tried multiple OnRowEditing, OnRowUpdating, OnRowUpdate as the button control.
Here is the code I use to that.
protected void gvReviewedPolicy_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DateTime dateTime = DateTime.Now;
//GridViewRow editRow = gvReviewedPolicy.Rows[gvReviewedPolicy.EditIndex];
//string Emailed = editRow.Cells[7].Text;
//string UniqClient = editRow.Cells[1].Text;
//string UniqPolicy = editRow.Cells[3].Text;
string UniqClient = gvReviewedPolicy.SelectedRow.Cells[2].Text;
string UniqPolicy = gvReviewedPolicy.SelectedRow.Cells[3].Text;
//string Email = Emailed.ToString();
//string dt = dateTime.ToString();
//string Up = UniqClient.ToString();
MessageBox.Show(UniqClient);
MessageBox.Show(UniqPolicy);
//MessageBox.Show(dt);
string query = "UPDATE [Reviewed_Renewal_Policy] SET [DateUpdated] = #dateTime where ([UniqClient] = #UniqClient) AND ([UniqPolicy] = #UniqPolicy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=TestDB;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqClient", UniqClient);
comm.Parameters.AddWithValue("#UniqPolicy", UniqPolicy);
//comm.Parameters.AddWithValue("#Emailed", Emailed);
comm.Parameters.AddWithValue("#dateTime", dateTime);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
}
I have some commented out because I was trying different things. However, the code that says
GridViewRow editRow = gvReviewedPolicy.Rows[gvReviewedPolicy.EditIndex];
string Emailed = editRow.Cells[7].Text;
string UniqClient = editRow.Cells[1].Text;
string UniqPolicy = editRow.Cells[3].Text;
It's supposed to access the values in those cells when UPDATE button is pushed. However, using MessageBox.Show , comes back blank.
Anyone have any idea how I can capture those values after hitting Edit, then the default UPDATE button?
I've tried to make that Winforms Datagrid usable for "write through" in the past, by implementing an DataGridView subclass (this allows you to access everything) but since immutable databases and queue transactions came into view, my Access-flavour DataGrid did not survive modern paradigm. Nowadays I tend to support ASP.NET MVC 5 to "edit" databases.
Anyway have you considered to connect a DataSource ? You don't have to access cells.. you can update using a connection like
private SqlDataAdapter daGrid = new SqlDataAdapter();
and this type of approach, you will have to fill in the details yourself, the complete code consists of several classes and is too large to post,
protected void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
/// .. perform actions according to keyboard events ..
/// .. for example below one ..
}
public override void UpdateAfterEditGrid(DataSet ds, DataGridView dataGridView1, bool DoRestoreCursor)
{
if (daGrid != null)
{
if (conn.State == ConnectionState.Closed) conn.Open();
dataGridView1.EndEdit();
try
{
if (ds == null)
{
//DataGridView dgv = dataGridView1;
//Console.WriteLine("Go datasource update .. " + dgv[cColumnIndex, cRowIndex].Value);
daGrid.Update((DataTable)dataGridView1.DataSource);
}
else daGrid.Update(ds);
LoadGridRestoreCursor(dataGridView1, DoRestoreCursor);
}
catch { ErrorReporting.ErrorMessage("== cannot update this content =="); }
}
}

button_click event from asp textbox only sending one number to sql stored procedure, why is my code not sending all characters?

I have the below code-behind for an asp web page:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["TapeTrackingConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand("UpdateContainerBySID", con);
cmd.CommandType = CommandType.StoredProcedure;
// If you are passing any parameters to your Stored procedure
// cmd.Parameters.AddWithValue("#Parameter_name", Parameter_value);
// int Session = int.Parse(DropDownList1.Text);
// int Container = int.Parse(ContainerID.Text);
cmd.Parameters.AddWithValue("#ContainerID", ContainerID.Text);
cmd.Parameters.AddWithValue("#SessionID", DropDownList1.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The #ContainerID shows all numbers input into the asp textbox, and a Response.Write shows all the characters. However, when I check the database after the button click, it has only inserted the first number, not the whole number. ie: instead of 43263, it is inserting 4.
Here is the textbox and submit button code:
<asp:TextBox ID="ContainerID" MaxLength="10" runat="server" Columns="6" Rows="1" TextMode="Number"></asp:TextBox>
<asp:Button runat="server" Text="Submit" OnClick="Button1_Click" ></asp:Button>
I am a bit new to this, so I do appreciate the help!!!
Thanks!!
Jack

Bind data using Repeater in c# ASP.NET

I need to bind some data on view page and the data will fetch from database using c# asp.net.I tried to implement Repeater but i can not know how to bind multiple data inside it.the following is my original view file.
index.aspx:
<div class="wpb_wrapper text-justify">
<asp:Repeater runat="server" ID="rptMissionId" >
<ItemTemplate>
<img src="pic/our-phylosophy.jpg" width="260" height="246" alt="" class="alignleft">
<h1>
<b>Heading</b>
</h1>
<p>
description
</p>
<br/>
<h1>
<b>Heading</b>
</h1>
<p>
description
</p><br>
</ItemTemplate>
</asp:Repeater>
</div>
In the above section one image is present and two set of data also there.Here i need to fetch image from database and set here in image place similarly heading and description in their proper place.My requirement is the last row of table image will set here and the heading,description of last two row will set here.
I am using 3-tire architecture here so please check my below code.
index.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
indexBL objMissionBl = new indexBL();
rptMissionId.DataSource = objMissionBl.getMissionData();
rptMissionId.DataBind();
}
indexBL.cs:
private indexDL objMissionDL = new indexDL();
public DataSet getMissionData()
{
try
{
DataSet ds = objMissionDL.getMissionData();
return ds;
}
catch (Exception e)
{
throw e;
}
}
IndexDL.cs:
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getMissionData()
{
con.Open();
try
{
DataSet ds = new DataSet();
string sql = "SELECT TOP 1 * FROM T_Mission_Vission WHERE Heading='Mission' ORDER BY Mission_vision_ID DESC";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
con.Close();
return ds;
}
catch (Exception e)
{
throw e;
}
}
I explained my requirement,if something is wrong or need to add please change it and help me to resolve this.Thanks.

Dropdownlist date format

I am using a DataTable to populate a dropdownlist on my web form, as well as using a stored procedure to query the database. The list retrieves only one field from the database and will be used in conjunction with a gridview to view all reservations made on a specific date.
Everything works fine, except for the format of the date. Right now it is showing the date as well as hours, minutes, and seconds. I have tried using the DataFormatString property the the web form but no luck.
Webform:
<b>Please select a date:</b>
<asp:DropDownList ID="ddlDateSelection" runat="server" DataFormatString="{0:MM/dd/yyyy}"></asp:DropDownList>
<br />
<asp:Label ID="lblError" runat="server" CssClass="validate"></asp:Label>
code behind used to query database:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
loadDates();
}
protected void loadDates()
{
DataTable dates = new DataTable();
using (SqlConnection con = new SqlConnection(DBAccess.GetConnectionString()))
{
SqlCommand cmd = new SqlCommand("usp_sel_ReservationDates", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dates);
ddlDateSelection.DataSource = dates;
ddlDateSelection.DataTextField = "ReservationDate";
ddlDateSelection.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Something bad has happened. Please try again.<br />Message: " + ex;
}
}
ddlDateSelection.Items.Insert(0, new ListItem("Please Select", "0"));
}
Any help would be greatly appreciated, as this is a learning project for myself. Thanks
Probably you need to refer to the correct property
<asp:DropDownList ID="ddlDateSelection" runat="server"
DataTextFormatString="{0:MM/dd/yyyy}">
</asp:DropDownList>
DropDownList properties
You can edit your SQL code to return only date
SELECT CONVERT (DATE, GETDATE())
 
RESULT: 2013-07-14

ASP.net Drop Down List Populating More Than Once on Refresh

I'm sorry for the trivial question, but I cannot find info about this on Google, or in my reference books, which accurately describes/solves my problem.
I have some DropDownList controls on a page, that I am populating with info from a SQL table. When the page is refreshed, the DropDownLists don't lose their old values, but instead get the same values added to them all over again, so now they are double populated. The functionality all still works the same, but it makes the DropDownList controls look less neat and obviously is unwanted.
<asp:DropDownList ID="DropDownList2" runat="server" OnLoad="LoadDutchessSubjects"
AppendDataBoundItems="true">
The LoadDutchessSubjects function in my code behind just grabs all records from the SQL table and loads them into the DDL:
public void LoadDutchessSubjects(object sender, EventArgs e)
{
string connectionString = SqlHelperClass.ConnectionString;
DataTable subjects = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM cfhudson_counties ORDER BY County", con);
adapter.Fill(subjects);
DropDownList2.DataSource = subjects;
DropDownList2.DataTextField = "County";
DropDownList2.DataValueField = "County";
DropDownList2.DataBind();
}
catch (Exception ex)
{
DropDownList2.Items.Insert(0, new ListItem("<ERROR: Occured in populating.>", "1"));
}
con.Close();
}
//Overall.Items.Insert(0, new ListItem("<Select Subject>", "0")); //(dev test)
}
Is there something I can do in the Code Behind to prevent this from happening? Does this have to do with ASP.net state and refreshing/what's going on server side? Maybe we can turn this question into a more useful and general explanation of why this is happening in the first place, because I evidently don't understand some important thing about ASP.net here.
do not reload the items on postbacks. they are persisted in viewstate
public void LoadDutchessSubjects(object sender, EventArgs e)
{
if (IsPostback)
return;
string connectionString = SqlHelperClass.ConnectionString;
DataTable subjects = new DataTable();

Categories