Dynamically updating database records - c#

It shows no error until and unless i add a record, it goes into catching exception which gives me connection problem as output. I tried alot but couldn't find my mistake.This is my code:
public partial class Default2 : System.Web.UI.Page
{
private string conStr = WebConfigurationManager.ConnectionStrings["StudentConnectionString1"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
FillList();
BtnsActive(false, true, false, false, false, false);
}
}
protected void BtnsActive(bool a, bool b, bool c, bool d, bool e, bool f)
{
Panel2.Enabled = a;
btnAdd.Enabled = b;
btnInsert.Enabled = c;
btnEdit.Enabled = d;
btnUpdate.Enabled = e;
btnDelete.Enabled = f;
}
protected void FillList()
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Select * from Student order by StudId", con);
SqlDataReader reader;
DropDownList1.Items.Clear();
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem = new ListItem();
newItem.Text = reader["StudId"] + "," + reader["StudFirstName"];
newItem.Value = reader["StudId"].ToString();
DropDownList1.Items.Add(newItem);
}
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Select * from Student where StudId='" + DropDownList1.SelectedValue + "'", con);
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
reader.Read();
TextBox1.Text = reader["StudId"].ToString();
TextBox2.Text = reader["StudFirstName"].ToString();
CheckBox1.Checked = (bool)reader["Library"];
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, true, false, true);
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
BtnsActive(true, false, true, false, false, false);
TextBox1.Text = "";
TextBox2.Text = "";
CheckBox1.Checked = false;
}
protected void btnInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Insert into Student (StudId,StudFirstName,Library) values(#sid,#name,#library)", con);
cmd.Parameters.AddWithValue("#sid", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
cmd.Parameters.AddWithValue("#library", CheckBox1.Checked);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('Record has been added.');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, false, false, false);
FillList();
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
BtnsActive(true, false, false, false, true, false);
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Update Student set StudId=#id,StudFirstName=#name,Library=#library) where StudId=#oldId", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
cmd.Parameters.AddWithValue("#name", TextBox2.Text);
cmd.Parameters.AddWithValue("#library", CheckBox1.Checked);
cmd.Parameters.AddWithValue("#oldId", DropDownList1.SelectedValue);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('The Record has been Updated.');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, false, false, false);
FillList();
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("Delete from Student where StudId=#id", con);
cmd.Parameters.AddWithValue("#id", TextBox1.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>alert('The Record has been Deleted.');</script>");
}
catch (Exception er)
{
Response.Write("<script language='javascript'>alert('Connection Problem');</script>");
}
finally
{
con.Close();
BtnsActive(false, true, false, false, false, false);
FillList();
}
}
}
and this is my design code which is simple..
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server" BackColor="#CC3300">
Stud ID:<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click" Text="Add" />
<asp:Button ID="btnInsert" runat="server" OnClick="btnInsert_Click" Text="Insert" />
<asp:Button ID="btnEdit" runat="server" OnClick="btnEdit_Click" Text="Edit" />
<asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete" />
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" BackColor="#FF9933">
<br />
<br />
Stud ID:
<asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
<br />
Name:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
Library :
<asp:CheckBox ID="CheckBox1" runat="server" />
</asp:Panel>
</div>
</form>
</body>
</html>

Related

Move selected items from one listbox to another in C#

This code re-initialize ListBox1 when append new item after Savepnusers complete successfully.
Writing value in TextBox this value is appended on the ListBox1.
But I can't get all values or single value from ListBox1 to ListBox2, because the append new item disappears from ListBox1.
Please see this:
My complete code below.
Any suggestions?
.cs page
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Threading;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default : System.Web.UI.Page
{
string sql;
ArrayList arraylist1 = new ArrayList();
ArrayList arraylist2 = new ArrayList();
protected void btn4_Click(object sender, EventArgs e)
{
while (ListBox2.Items.Count != 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
protected void btn3_Click(object sender, EventArgs e)
{
arraylist2 = new ArrayList();
if (ListBox2.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
if (!arraylist2.Contains(ListBox2.Items[i]))
{
arraylist2.Add(ListBox2.Items[i]);
}
}
}
for (int i = 0; i < arraylist2.Count; i++)
{
if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
{
ListBox1.Items.Add(((ListItem)arraylist2[i]));
}
ListBox2.Items.Remove(((ListItem)arraylist2[i]));
}
ListBox1.SelectedIndex = -1;
}
}
protected void btn2_Click(object sender, EventArgs e)
{
while (ListBox1.Items.Count != 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
arraylist1 = new ArrayList();
if (ListBox1.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]);
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
}
private void MTListBox1()
{
DataTable dt = new DataTable();
sql = #String.Format(" SELECT NAME FROM `country` GROUP BY `NAME` ORDER BY SURFACEAREA DESC LIMIT 10; ");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
OdbcDataAdapter sqlDa = new OdbcDataAdapter(command);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "NAME";
ListBox1.DataValueField = "NAME";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (OdbcException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
command.Connection.Close();
}
}
}
}
public class pnnusers
{
public string txuser { get; set; }
}
[WebMethod(EnableSession = true)]
[ScriptMethod]
public static void Savepnusers(pnnusers nnewuser)
{
string sql = #String.Format("INSERT INTO `stored` SELECT Name, NULL FROM Country WHERE Name=?;");
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand command =
new OdbcCommand(sql, cn))
{
try
{
command.Connection.Open();
command.Parameters.AddWithValue("param1", nnewuser.txuser.ToString());
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
command.Connection.Close();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MTListBox1();
}
}
}
.aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"
EnableEventValidation="false" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=imgsave]").bind("click", function () {
var qString = "?" + window.location.href.split("?")[1];
var nnewuser = {};
nnewuser.txuser = $("[id*=txuser]").val();
var txtUser = $("[id*=txuser]").val();
$.ajax({
type: "POST",
url: "Default.aspx/Savepnusers" + qString,
data: '{nnewuser: ' + JSON.stringify(nnewuser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if ($("[id*=txuser]").val()) {
alert("OK");
alert(JSON.stringify(nnewuser));
if (txtUser) {
$("[id*=ListBox1]").append("<option value='" + nnewuser.txuser + "'>" + nnewuser.txuser + "</option>");
}
}
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error : " + thrownError + JSON.stringify(nnewuser));
}
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="align-content: center;">
<br />
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<br />
<asp:ImageButton ID="imgsave" runat="server"
ImageUrl="/ImgFolder/Img.gif"
OnClientClick="if (!confirm('Are you sure?')) return false;" />
<br />
LISTBOX1
<br />
<div>
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
LISTBOX2
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
</div>
<br />
<div style="align-content: center;">
<asp:Button ID="btn1" runat="server" Text=">" OnClick="btn1_Click" Width="100" />
<br />
<asp:Button ID="btn2" runat="server" Text=">>" OnClick="btn2_Click" Width="100" />
<br />
<asp:Button ID="btn3" runat="server" Text="<" OnClick="btn3_Click" Width="100" />
<br />
<asp:Button ID="btn4" runat="server" Text="<<" OnClick="btn4_Click" Width="100" />
</div>
</div>
</form>
</body>
</html>
According to your description and codes,as far as I think,the problem is when you click the button,the page will be refresh and the listbox coudn't get the current data.
I suggest you could use button click to insert data to database intead of ajax.
More details, you could refer to below codes:
<form id="form1" runat="server">
<div style="align-content: center;">
<br />
<asp:TextBox ID="txuser" runat="server" BackColor="Yellow" CssClass="pure-u-23-24"></asp:TextBox>
<br />
<asp:Button ID="imgsave" runat="server"
OnClientClick="return confirm('Are you sure?');" OnClick="imgsave_Click" />
<br />
LISTBOX1
<br />
<div>
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
LISTBOX2
<asp:ListBox ID="ListBox2" runat="server"
SelectionMode="Multiple"
Height="250" Width="400"></asp:ListBox>
</div>
<br />
<div style="align-content: center;">
<asp:Button ID="btn1" runat="server" Text=">" OnClick="btn1_Click" Width="100" />
<br />
<asp:Button ID="btn2" runat="server" Text=">>" OnClick="btn2_Click" Width="100" />
<br />
<asp:Button ID="btn3" runat="server" Text="<" OnClick="btn3_Click" Width="100" />
<br />
<asp:Button ID="btn4" runat="server" Text="<<" OnClick="btn4_Click" Width="100" />
</div>
</div>
</form>
Code-behind:
string sql;
ArrayList arraylist1 = new ArrayList();
ArrayList arraylist2 = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
MTListBox1();
}
}
protected void btn1_Click(object sender, EventArgs e)
{
arraylist1 = new ArrayList();
if (ListBox1.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if (ListBox1.Items[i].Selected)
{
if (!arraylist1.Contains(ListBox1.Items[i]))
{
arraylist1.Add(ListBox1.Items[i]);
}
}
}
for (int i = 0; i < arraylist1.Count; i++)
{
if (!ListBox2.Items.Contains(((ListItem)arraylist1[i])))
{
ListBox2.Items.Add(((ListItem)arraylist1[i]));
}
ListBox1.Items.Remove(((ListItem)arraylist1[i]));
}
ListBox2.SelectedIndex = -1;
}
}
protected void btn2_Click(object sender, EventArgs e)
{
while (ListBox1.Items.Count != 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListBox2.Items.Add(ListBox1.Items[i]);
ListBox1.Items.Remove(ListBox1.Items[i]);
}
}
}
protected void btn3_Click(object sender, EventArgs e)
{
arraylist2 = new ArrayList();
if (ListBox2.SelectedIndex >= 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
if (ListBox2.Items[i].Selected)
{
if (!arraylist2.Contains(ListBox2.Items[i]))
{
arraylist2.Add(ListBox2.Items[i]);
}
}
}
for (int i = 0; i < arraylist2.Count; i++)
{
if (!ListBox1.Items.Contains(((ListItem)arraylist2[i])))
{
ListBox1.Items.Add(((ListItem)arraylist2[i]));
}
ListBox2.Items.Remove(((ListItem)arraylist2[i]));
}
ListBox1.SelectedIndex = -1;
}
}
protected void btn4_Click(object sender, EventArgs e)
{
while (ListBox2.Items.Count != 0)
{
for (int i = 0; i < ListBox2.Items.Count; i++)
{
ListBox1.Items.Add(ListBox2.Items[i]);
ListBox2.Items.Remove(ListBox2.Items[i]);
}
}
}
protected void MTListBox1()
{
string str, strSql;
str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
SqlConnection conn = new SqlConnection(str);
strSql = "select Name from stored";
SqlCommand cmd = new SqlCommand(strSql, conn);
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
ListBox1.DataTextField = "NAME";
ListBox1.DataValueField = "NAME";
ListBox1.DataSource = dt;
ListBox1.DataBind();
}
}
catch (Exception ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
public class pnnusers
{
public string txuser { get; set; }
}
protected void imgsave_Click(object sender, EventArgs e)
{
string sql = "INSERT INTO stored(Name) values(#param1)";
string str;
str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
SqlConnection conn = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Parameters.AddWithValue("param1", txuser.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
MTListBox1();
}
Result:

asp.net panel control visibility issue

I have written a code which checks unique ID availability status.. if ID is available it should make panel visible otherwise the panel visibility is hidden. But it is not working. If i set panel visibility to false in page load it works.. but panel visibility code inside text change event of textbox, doesnt work. In my view page script manager is present to update content inside update panel. What am i doing wrong.
<asp:ScriptManager ID="scriptmanager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="PnlUsrDetails" runat="server">
<ContentTemplate>
<table>
<tr>
Enter unique no: <asp:TextBox ID="txtUniqueNo" runat="server" AutoPostBack="true" ontextchanged="txtUniqueNo_TextChanged"/>
</tr>
<tr>
<div id="checkusername" runat="server" Visible="false">
<asp:Image ID="imgstatus" runat="server" Width="17px" Height="17px"/>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</div>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="Panel1" runat="server">
<div>Panel content</div>
</asp:Panel>
server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
Panel1.Visible = false;
PopulateCategory();
getSubCategories(CategoryDropDownList.SelectedValue);
//CategoryDropDownList_SelectedIndexChanged(null, null);
}
}
protected void txtUniqueNo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUniqueNo.Text))
{
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcCommand cmd = new OdbcCommand("select * from gallery where unique_no='" + txtUniqueNo.Text + "'", conn);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
Panel1.Visible = false;
imgstatus.ImageUrl = "~/images/unavailable.png";
lblStatus.Text = "Unique Id Already Taken";
}
else
{
try
{
checkusername.Visible = true;
Panel1.Visible = true;
imgstatus.ImageUrl = "~/images/tick.png";
lblStatus.Text = "Unique Id Available";
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
}
else
{
checkusername.Visible = false;
}
}
My file upload is also in update panel,, which loses its file on upload. Suggest me any alternative approaches to achieve this functionality...
Thanks
Problably cause the Control is not rendered (visible=false) and no viewstate is saved before.
Try to hide and show it with styles:
First:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
//Panel1.Visible = false; Comment
PopulateCategory();
getSubCategories(CategoryDropDownList.SelectedValue);
//CategoryDropDownList_SelectedIndexChanged(null, null);
}
}
protected void txtUniqueNo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUniqueNo.Text))
{
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcCommand cmd = new OdbcCommand("select * from gallery where unique_no='" + txtUniqueNo.Text + "'", conn);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
Panel1.Style.Add("display", "none");
imgstatus.ImageUrl = "~/images/unavailable.png";
lblStatus.Text = "Unique Id Already Taken";
}
else
{
try
{
checkusername.Visible = true;
Panel1.Style.Add("display", "block");
imgstatus.ImageUrl = "~/images/tick.png";
lblStatus.Text = "Unique Id Available";
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
}
else
{
checkusername.Visible = false;
}
}
File upload control will not work inside Update panel in this case it will lose selected file for sure.Since you have asked for alternative approach.One way is to check unique no availablity using jquery. Here is the perfect working link Check-UserName-Availability-jquery to check username availability. use this example to check unique no.
Ajax has success and error methods, so you can place your form inside a div with unique id and toggle its visibility on ajax result.
Upoo the success of ajax you can show your div in which form is present. This will eliminate the need to use script manager and update panel.

Insert the data when user click on select button inside the gridview

I have a gridview as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True"
OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand" OnRowDataBound="gvDoctorList_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />--%>
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
Code behind gridview rowcommand is as below
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
string pIDstr = Convert.ToString(Session["PatientId"]);
if (!string.IsNullOrEmpty(pIDstr))
{
int patientID = Convert.ToInt32(pID);
//string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connection))
{
//SqlConnection conn = new SqlConnection(con);
DataSet ds;
ds = new DataSet();
SqlDataAdapter cmpatientexam;
conn.Open();
cmpatientexam = new SqlDataAdapter(sqlquery, conn);
cmpatientexam.Fill(ds, "PatientExam");
TreeNode pidnode = new TreeNode();
pidnode.Text = pIDstr;
foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
{
//TreeNode tvpatexam = new TreeNode();
//tvpatexam.Text = patrow["PId"].ToString();
//TreeView1.Nodes.Add(tvpatexam);
//for (int i = 0; i < ds.Tables["PatientExam"].Columns["PId"].Count; i++)
//if (patrow["PId"].ToString() != DBNull.Value)
//{
TreeNode childtvpatexam = new TreeNode();
childtvpatexam.Text = patrow["Exam"].ToString();
pidnode.ChildNodes.Add(childtvpatexam);
//break;
//}
//TreeView1.Nodes.Add(tvpatexam);
}
TreeView1.Nodes.Add(pidnode);
ds.Dispose();
cmpatientexam.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Code behind the button click event is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I want to insert the value which is selected from gridview using select button and insert that selected value on button click event....but with the above code it is not working...
Can anyone suggest me some other idea or if possible with these code then how...can you give me the code for it....Thanks a lot
You can add a hidden field and save Gridview's rowindex in the hidden field. In btnformatric_Click you can get the row by index and get the data. The markup:
<asp:HiddenField ID="hdnRowIndex" runat="server" Value ="" />
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
In code, gvDoctorList_RowCommand method:
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
hdnRowIndex.Value = gvr.RowIndex.ToString();
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
btnformatric_Click method:
protected void btnformatric_Click(object sender, EventArgs e)
{
int rowIndex = 0;
if (int.TryParse(hdnRowIndex.Value, out rowIndex))
{
//Get the row
GridViewRow row = gvDoctorList.Rows[rowIndex];
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I presume that you're interested in inserting a record based on the selected PatientID value from the GridView?
What you want to do is start by setting the GridView's DataKeyNames property to PatientID like so:
<asp:GridView ID="gvDoctorList" runat="server" DataKeyNames="PatientID" ...>
Then in the btnformatric_Click event handler you can get the selected PatientID value via gvDoctorList.SelectedValue, as in:
string pIDstr = gvDoctorList.SelectedValue.ToString();
Of course, before you do the above you should check to make sure that the user has selected a patient from the grid (namely, that gvDoctorList.SelectedIndex >= 0).

How to Edit,Update and Delete Rows in GridView in ASP.NET

I am retrieving Data From Database into GridView.
I don't know how to Edit and Delete row in GridView and it Also Update in Database.
Also please Tell me if their is any mistake in my Code
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 248px;
}
.style2
{
width: 100%;
}
.style3
{
height: 180px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="style3">
<h1 align="center">Students Personal Information
</h1>
<table class="style2">
<tr>
<td class="style1">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<asp:Button ID="Button1" runat="server" Text="Insert Data"
onclick="Button1_Click" />
</td>
<td>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Students" Width="128px" />
</td>
</tr>
</table>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
<br />
<asp:GridView ID="GridView1" runat="server"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
enter code here
And my back-end code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Data Source=DATA_NET_81_SOF;Initial
Catalog=Students;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = "Student's Name";
Label2.Text = "Student's Class";
Label3.Text = "Student's Roll Number";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", conn);
conn.Open();
cmd.Parameters.AddWithValue("StudentName", TextBox1.Text);
cmd.Parameters.AddWithValue("StudentClass", TextBox2.Text);
cmd.Parameters.AddWithValue("StudentRollno", TextBox3.Text);
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlCommand sql = new SqlCommand("Select * from Personalinfo", conn);
SqlDataAdapter da = new SqlDataAdapter(sql);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = (ds);
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
}
private string connection = #"...";
protected void Button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connection))
{
try
{
SqlCommand cmd = new SqlCommand("Insert INTO Personalinfo(StudentName,StudentClass,StudentRollNo)values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
Label4.Text = "Data Is Stored";
}
catch (Exception ex)
{
Label4.Text = ex.Message;
}
}
}
For Update -->
protected void Button_Update(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "UPDATE Personalinfo SET StudentName = #1 ... WHERE Student_Id= #N";
cmd.Parameters.Add("#1",SqlDbType.NVarChar).Value = your_value;
cmd.Para.....
cmd.Parameters.Add("#N",.....).Value = your_student_id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
For Delete -->>
protected void Button_Delete(object sender, EventArgs e){
using(SqlConnection con = new SqlConnection(conn))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = "DELETE FROM Personalinfo WHERE StudentName = '"+TextBox1.Text+"'";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
After every event of button you can make a BindGrid ... to refresh your data from data grid... in BindGrid method you need to remake the select method you just did ... if you have issue tell me

null value in findcontrol of gridview, item template confusion

I have Template Field for gridview as below:
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtBonus" runat="server"></asp:TextBox>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
</EditItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
When i am in gv_RowUpdating event, i wanted to take the value of edited field by findcontrol.
For that i am using following code:
`TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");`
But each time it is showing me null value in txtUname when i debug the code.
What can be the problem?
Full Event Code:
protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtUname = (TextBox)gv.Rows[e.RowIndex].FindControl("txtEmpName");
float bonus = float.Parse(gv.DataKeys[e.RowIndex].Values["bonus"].ToString());
try
{
cmd = new SqlCommand("update emp set empName=#eName");
cmd.parameters.AddParametersWithValue("#eName",txtUname.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
}
catch (Exception ex)
{
}
}
EDIT
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection("Data Source=192.168.51.71;Initial Catalog=WebBasedNewSoft;User ID=sa;password=prabhu");
BindGrid();
}
private void BindGrid()
{
try
{
da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
string eName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
try
{
con.Open();
cmd = new SqlCommand("update emp set empName='"+eName+"'",con);
cmd.ExecuteNonQuery();
con.Close();
}
catch(Exception ex)
{
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
}
refer this
http://www.codeproject.com/Articles/37207/Editable-Gridview-with-Textbox-CheckBox-Radio-Butt
also put your code for Edit command. it might be RowEditing or RowCommand

Categories