Make ASP Validators validate just one gridview row? - c#

I am making a little website for myself and within this website you can make users. The moment you add a user it goes into a database. You can also see the existing users in a gridview, so when you make a new user it goes into the gridview. But one little problem, when I try and use validators within this gridview, it validates every row. I need it to validate just one row. Someone said something about row ID, but i don't know how to make that work.
As you can see I've tried some stuff with RowIndex, but couldn' t get it to work
Any help is appreciated
Management.Aspx :
<asp:GridView runat="server" ID="gridUsers" AutoGenerateColumns="False" DataKeyNames="username" DataSourceID="DSUserList" OnRowCommand="gridUsers_RowCommand">
<Columns>
<asp:BoundField DataField="username" HeaderText="Gebruikersnaam" ReadOnly="True" SortExpression="username"></asp:BoundField>
<asp:BoundField DataField="display_name" HeaderText="Naam" SortExpression="display_name"></asp:BoundField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button OnClientClick="ConfirmDeleteAdmin()" Text="Verwijderen" runat="server" id="btnDeleteUser" CommandName="delUser" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" id="txtChangePassword" />
<%-- TODO: Mike: Validators via code --%>
<asp:Button OnClientClick="ConfirmChangePassword()" ValidationGroup="vgChangePW" Text="Wachtwoord wijzigen" runat="server" ID="btnChangePassword" CommandName="changePassword" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<%-- <asp:RequiredFieldValidator ID="rfChangePassReq" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>U heeft geen nieuw wachtwoord ingevoerd"></asp:RequiredFieldValidator>--%>
<%-- asp:RegularExpressionValidator ID="rfChangePassReg" ValidationExpression="^(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$" ControlToValidate="<%# String.Format("txtChangePW{0}",((GridViewRow) Container).RowIndex).ToString() %>" ValidationGroup="vgChangePW" runat="server" ErrorMessage="<br/>Uw wachtwoord moet uit minimaal 6 tekenen bestaan en moet minimaal 1 hoofdletter en 1 cijfer bevatten"></asp:RegularExpressionValidator>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Management.aspx.cs :
protected void btnCreateUser_Click(object sender, EventArgs e)
{
try {
connection.Open();
} catch (Exception) {}
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_add_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = txtUsername.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#displayName", SqlDbType.NVarChar, 100).Value = txtDisplayName.Text;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0)
{
lblNewUserStatus.Text = "Gebruiker bestaat al";
lblNewUserStatus.ForeColor = Color.Red;
}
else
{
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
lblNewUserStatus.Text = "Gebruiker toegevoegd";
lblNewUserStatus.ForeColor = Color.Black;
txtUsername.Text = "";
txtPassword.Text = "";
txtDisplayName.Text = "";
}
connection.Close();
}
protected void gridUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
// Deletes user or changes a password of a user
if (e.CommandName == "delUser")
{
string confirmValue = Request.Form["delete_admin"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String usernameToDelete = row.Cells[0].Text;
try {
connection.Open();
} catch (Exception) { }
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = connection;
cmd.CommandText = "sp_delete_user";
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = usernameToDelete;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
//Failed
lblDelteStatus.Text = "Kan gebruiker admin niet verwijderen";
lblDelteStatus.ForeColor = Color.Red;
} else {
// Deleted
lblDelteStatus.Text = "Gebruiker verwijderd";
lblDelteStatus.ForeColor = Color.Black;
// Reload user list
DSUserList.EnableCaching = false;
gridUsers.DataBind();
DSUserList.EnableCaching = true;
}
connection.Close();
if (usernameToDelete == Session["username"].ToString()) {
ProjectManager.logout();
Page.Response.Redirect(Page.Request.Url.ToString());
}
}
}
else if (e.CommandName == "changePassword")
{
string confirmValue = Request.Form["change_password"];
if (confirmValue == "Yes") {
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gridUsers.Rows[index];
String username = row.Cells[0].Text;
TextBox txtPassword = (TextBox)row.Cells[3].FindControl("txtChangePassword");
String password = txtPassword.Text.Trim();
password = password != "" ? ProjectManager.GetSHA1HashData(password) : "";
try {
connection.Open();
} catch (Exception) { }
cmd.Connection = connection;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_change_password";
cmd.Parameters.Add("#password", SqlDbType.NVarChar, 100).Value = password;
cmd.Parameters.Add("#username", SqlDbType.NVarChar, 100).Value = username;
cmd.Parameters.Add("#return_value", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
int code = int.Parse(cmd.Parameters["#return_value"].Value.ToString());
if (code == 0) {
lblDelteStatus.Text = "Dit wachtwoord is onlangs gebruikt, kies een ander wachtwoord";
lblDelteStatus.ForeColor = Color.Red;
} else if (code == 1) {
lblDelteStatus.Text = "Wachtwoord gewijzigd";
lblDelteStatus.ForeColor = Color.Black;
}
connection.Close();
}
}
}

Try this in the RowDataBound event:
Create a row specific validation group name that is a concatenation of some prefix and the row index and assign it to each validator and control in the row that is part of the validation group... i.e.:
valGroupName = string.format("vgRow{0}", e.row.rowindex.tostring);
Button btn = e.row.FindControl("btnChangePassword");
btn.ValidationGroup = valGroupName
RequiredFieldValidator vreq = e.row.FindControl("rfChangePassReq");
vreq.ValidationGroup = valGroupName
RegularExpressionValidator vregx = e.row.FindControl("rfChangePassReg");
vregx.ValidationGroup = valGroupName
...etc...
This way only validation for the specific row should be triggered when you select the row button to save.
I don't recall and I can't test it right now, but you may have an issue with any field that is connected to a RequiredFieldValidator, it may prevent posting. You'll have to check that out. You might be ok as they will be part of a different validation group.

Related

Trying to check checkbox but in if condition it appears not to be checked

I want to check a row(s) that i will lather update, but when i get to if condition it appears if it is not checked.
<asp:TemplateField HeaderText="Stock" ItemStyle-Width="72px" HeaderStyle-Width="72px">
<ItemTemplate>
<asp:CheckBox ID="InStockCbx" runat="server" />
</ItemTemplate>
</asp:TemplateField>
protected void UsedForButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkBox = row.FindControl("InStockCbx") as CheckBox;
if (chkBox.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value.ToString());
conn.Open();
SqlCommand comm = new SqlCommand("UPDATE WorkTable SET InStock = 0, UsedOrder = #UsedOrder WHERE Id=#ID", conn);
comm.CommandType = CommandType.Text;
comm.Parameters.Add("#ID", SqlDbType.Int, 1).Value = id;
comm.Parameters.Add("#UsedOrder", SqlDbType.VarChar).Value = UsedForTextBox.Text;
comm.ExecuteNonQuery();
conn.Close();

How to avoid inserting the unwanted values to database?

I want to insert only the selected value but when I save its inserting all the values in database.
In the above database in subject column I want only the subject which has the faculty.But in my database all the subjects are inserting.
I am using boundfield for the subject column in GridView. My code so far`
<asp:GridView ID="Gvassignsubject" runat="server" AutoGenerateColumns="False" OnRowDataBound="Gvassignsubject_RowDataBound">
<Columns>
<asp:BoundField DataField="Subject" HeaderText="subject" SortExpression="subject" />
<asp:TemplateField HeaderText ="Faculty">
<ItemTemplate>
<asp:Label ID ="lblfaculty" runat="server" Text='<%%# Eval("facultyname") %>>' Visible="false"/>
<asp:DropDownList ID="ddlfaculty" runat="server"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Set Hour">
<ItemTemplate>
<asp:TextBox ID="txthour" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
protected void btnsubmit_Click(object sender, EventArgs e)
{
using (SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
foreach (GridViewRow r in Gvassignsubject.Rows)
{
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string facultyname = ddlfaculty.SelectedValue;
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}
}
}
Its adding all the rows regardless because you have no criteria;
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
DropDownList ddlfaculty = (DropDownList)Gvassignsubject.Rows[i].FindControl("ddlfaculty");
string facultyname = ddlfaculty.SelectedValue;
if (!string.Equals(ddlfaculty.SelectedValue, "Please Select"))
{
string batch = ddlbatches.SelectedValue;
string subject = r.Cells[0].Text;
TextBox txthour = (TextBox)Gvassignsubject.Rows[i].FindControl("txthour");
string sethour = txthour.Text;
con2.Open();
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
con2.Close();
}
}
I believe you have to set default select list item value as null and check for it in your for loop:
for (int i = 0; i < Gvassignsubject.Rows.Count; i++)
{
if(!string.IsNullOrEmpty(ddlfaculty.SelectedValue)) {
...
}
}
You can put a condition that will check the value exist or not in the subject field. You can do this like below :
if(facultyname !="" && facultyname !="Please Select")
{
SqlCommand cmd = new SqlCommand("insert into assign (batch,facultyname,sethour,subject)values(#batch,#facultyname,#sethour,#subject)", con2);
cmd.Parameters.AddWithValue("#batch", batch);
cmd.Parameters.AddWithValue("#subject", subject);
cmd.Parameters.AddWithValue("#facultyname", facultyname);
cmd.Parameters.AddWithValue("#sethour", sethour);
cmd.Connection = con2;
cmd.ExecuteNonQuery();
}
This is considering the condition that the ddlfaculty dropdown
has the Value same as its Text.
Try this
if(ddlfaculty.selectedindex !=-1 )
{
do the insert function
}

asp.net - Server validation does not fire on first submission

I'm having the issue with my Custom Validator using the OnServerValidation. It does not fire when I first submit, but correctly fires afterwards.
In other words, even if I do not fill the data in my text field correctly and submit the first time around, the Validator does not catch the mistake and still accepts the data the field contains, but when I return the form, it then catches the inconsistency second time I submit.
I have 3 validators that validate this field. The other two validators work fine, its only the OnServer validation that is faulty.
My sample ASP Code is for editing is:
<asp:TemplateField HeaderText="End Date" SortExpression="end_date">
<EditItemTemplate>
<asp:TextBox ID="txtEndDate" runat="server" Text='<%# Bind("End_Date", "{0:MM/dd/yyyy}") %>'></asp:TextBox>
<asp:Image ID="imgEndDt" runat="server" ImageUrl="images/calendar.png" ImageAlign="Middle" />
<asp:Label ID="hvEndDate" runat="server" Text="?" ToolTip="blah" BackColor="#507CD1" ForeColor="White" Font-Bold="True" Height="15" Font-Underline="True"></asp:Label>
<asp:RegularExpressionValidator ID="revEndDate" runat="server"ErrorMessage="RegularExpressionValidator" ControlToValidate="txtEndDate" Text="(mm/dd/yyyy), ex: 06/03/2011." ValidationExpression="([1-9]|0[1-9]|1[012])[- /.]([1-9]|0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d"></asp:RegularExpressionValidator>
<cc1:CalendarExtender ID="ceTestDt5" runat="server" TargetControlID="txtEndDate" PopupButtonID="imgEndDt"></cc1:CalendarExtender><br />
<asp:CustomValidator ID="cvEndDate" runat="server" ErrorMessage="blah" ControlToValidate="txtEndDate" ValidateEmptyText="True" ClientValidationFunction="currentDt"></asp:CustomValidator>
<br /><asp:CustomValidator ID="cvExitDateCred" runat="server" ErrorMessage="blah" OnServerValidate="exitDateCheck_server" ControlToValidate="txtEndDate"></asp:CustomValidator>
</EditItemTemplate>
And my Code behind CS code is:
protected void exitDateCheck_server(object obj, ServerValidateEventArgs args)
{
args.IsValid = true;
Boolean hasCredEndDate = false;
String personExit = String.Empty;
if (dvPerson.FindControl("txtEndDate") != null)
{
personExit = (dvPerson.FindControl("txtEndDate") as TextBox).Text.Trim();
if (personExit != String.Empty)
{
try
{
SqlDataReader rdr = null;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("blah", con);
cmd.Parameters.Add("blah", SqlDbType.VarChar).Value = txtPPersonId.Text;
con.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
if (Int32.Parse(rdr["cnt"].ToString()) > 0)
{
hasCredEndDate = true;
}
}
cmd.Dispose();
con.Close();
if (hasCredEndDate == true)
{
args.IsValid = false;
SqlDataReader rdr2 = null;
SqlConnection con2 = new SqlConnection(constr);
SqlCommand cmd2 = new SqlCommand("blah, con2);
cmd2.Parameters.Add("blah", SqlDbType.VarChar).Value = txtPPersonId.Text;
cmd2.Parameters.Add("blah", SqlDbType.VarChar).Value = (dvPerson.FindControl("txtEndDate") as TextBox).Text;
con2.Open();
rdr2 = cmd2.ExecuteReader();
if (rdr2.Read())
{
if (Int32.Parse(rdr2["cnt"].ToString()) > 0)
{
args.IsValid = true;
}
}
cmd2.Dispose();
con2.Close();
}
}
catch (Exception e)
{
lblMessage.Text = e.ToString();
}
}
}
}
I apologize if I am leaving out any necessary information, I will add if needed.

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).

ASP.net Making Unbound column invisible

I'm trying to get a column in my unbound gridview to be invisible, specifically the id. I'm binding the grid with ADO.net, so I cant just set the tag in the html code to invisible. Here is some code...
protected void btn_search_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source=WILSON-PC; Initial Catalog=KamManOnline; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("SELECT oid, Supplier, DepartmentA, DepartmentB, DepartmentC, OrderNumber, CONVERT(varchar(10), PORecieptDate, 101) AS PORecieptDate, CONVERT(varchar(10), ProductRecieved, 101) AS ProductRecieved, CONVERT(varchar(10),POEntryDate, 101) AS POEntryDate FROM tbl_OrderD WHERE (Supplier = #Supplier OR #Supplier IS NULL) AND (DepartmentA = #DepartmentA OR #DepartmentA IS NULL) AND (OrderNumber = #OrderNumber OR #OrderNumber IS NULL) AND (PORecieptDate BETWEEN #FromA AND #ToA OR (#FromA IS NULL AND #ToA IS NULL)) AND (ProductRecieved BETWEEN #FromB AND #ToB OR (#FromB IS NULL AND #ToB IS NULL)) AND (POEntryDate BETWEEN #FromC AND #ToC OR (#FromC IS NULL AND #ToC IS NULL))", cs);
if (!chk_Suppliers.Checked) da.SelectCommand.Parameters.Add("#Supplier", SqlDbType.VarChar).Value = ddl_SupplierView.Text.ToString();
else da.SelectCommand.Parameters.Add("#Supplier", SqlDbType.VarChar).Value = DBNull.Value;
if (!chk_Departments.Checked) da.SelectCommand.Parameters.Add("#DepartmentA", SqlDbType.VarChar).Value = ddl_DepartmentView.Text.ToString();
else da.SelectCommand.Parameters.Add("#DepartmentA", SqlDbType.VarChar).Value = DBNull.Value;
if (txt_orderNumView.Text != "") da.SelectCommand.Parameters.Add("#OrderNumber", SqlDbType.VarChar).Value = txt_orderNumView.Text.ToString();
else da.SelectCommand.Parameters.Add("#OrderNumber", SqlDbType.VarChar).Value = DBNull.Value;
if (txt_PORecievedFrom.Text != "" && txt_PORecievedTo.Text != "")
{
da.SelectCommand.Parameters.Add("FromA", SqlDbType.SmallDateTime).Value = txt_PORecievedFrom.Text.ToString();
da.SelectCommand.Parameters.Add("ToA", SqlDbType.Date).Value = txt_PORecievedTo.Text.ToString();
}
else
{
da.SelectCommand.Parameters.Add("FromA", SqlDbType.Date).Value = DBNull.Value;
da.SelectCommand.Parameters.Add("ToA", SqlDbType.Date).Value = DBNull.Value;
}
if (txt_ProductRecievedFrom.Text != "" && txt_ProductRecievedTo.Text != "")
{
da.SelectCommand.Parameters.Add("FromB", SqlDbType.Date).Value = txt_PORecievedFrom.Text;
da.SelectCommand.Parameters.Add("ToB", SqlDbType.Date).Value = txt_PORecievedTo.Text;
}
else
{
da.SelectCommand.Parameters.Add("FromB", SqlDbType.Date).Value = DBNull.Value;
da.SelectCommand.Parameters.Add("ToB", SqlDbType.Date).Value = DBNull.Value;
}
if (txt_POEntryFrom.Text != "" && txt_poEntryTo.Text != "")
{
da.SelectCommand.Parameters.Add("FromC", SqlDbType.Date).Value = txt_PORecievedFrom.Text;
da.SelectCommand.Parameters.Add("ToC", SqlDbType.Date).Value = txt_PORecievedTo.Text;
}
else
{
da.SelectCommand.Parameters.Add("FromC", SqlDbType.Date).Value = DBNull.Value;
da.SelectCommand.Parameters.Add("ToC", SqlDbType.Date).Value = DBNull.Value;
}
ds.Clear();
da.Fill(ds);
gv_search.DataSource = ds.Tables[0];
gv_search.DataBind();
}
this is your basic good old ASP.net search function. However, in this gridview I enable selecting like this...
protected void gv_search_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("selectedOrder.aspx?oid=" + gv_search.SelectedValue.ToString());
}
I know I can set the oid to be the datakey tab. However, I want to make this invisible. I have tried this method here...
protected void gv_search_RowCreated(object sender, GridViewRowEventArgs e)
{
gv_search.Columns[0].Visible = false;
}
It gave me this error...
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Does anyone know how to do this? Thanks
Declare the columns you want displayed inside the aspx file. Tell the grid to not generate columns using the AutoGenerateColumns="False" property.
<asp:DataGrid id="DataGrid1"
runat="server" CssClass="grid"
AutoGenerateColumns="False">
<Columns>
<asp:BoundColumn
DataField="OrderID" ReadOnly="True"
HeaderText="Order ID" />
<asp:BoundColumn
DataField="ShipName" HeaderText="Ship to"
ReadOnly="True" />
<asp:BoundColumn
DataField="ShipCountry" HeaderText="Country"
ReadOnly="True" />
<asp:BoundColumn
DataField="ShipCountry" HeaderText="Country"
Visible="False" />
</Columns>
</asp:DataGrid>
Set the desired columns to Visible="False".
Change it to the DataBound event:
protected void gv_search_DataBound(object sender, EventArgs e)
{
gv_search.Columns[0].Visible = false;
}

Categories