I'm working on making customized gridviews with the use of dropdownlist and checkboxes. The checkboxes represent the columns in the database to call. My codebehind file is to create a customized SQL Query that I call back to the asp:DqlDataSource... SelectCommand=""
As of now I'm trying to store a message into (query) into a variable, this is where I'm currently stuck...
<asp:DropDownList ID="DDL" runat="server" DataSourceID="SqlDataSource1" 开发者_Go百科
DataTextField="Fullname" DataValueField="Employee_ID" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="@Query">
</asp:SqlDataSource>
<asp:CheckBox ID="Address" Text="Address" runat="server" />
<asp:CheckBox ID="Phone" Text="Phone" runat="server" />
<asp:CheckBox ID="Email" Text="Email" runat="server" />
<asp:Button ID="ButtonID" onclick="Create" runat="server" Text="Submit" />
<br />
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label> -
<asp:Label ID="Label2" runat="server" Text=""></asp:Label> -
<asp:Label ID="Label3" runat="server" Text=""></asp:Label> -
<asp:Label ID="Label4" runat="server" Text=""></asp:Label> -
<br />
<asp:Label ID="Label5" runat="server" Text=""></asp:Label>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
======================= CodeBehind ===========================
protected void Create(object sender, System.EventArgs e)
{
string a = "";
string b = "";
string c = "";
string d = "";
if (DDL.SelectedValue == "Select")
{
return;
}
else
{
a = DDL.SelectedValue;
}
if (Address.Checked == true)
{
b = "Address,";
}
if (Phone.Checked == true)
{
c = "Phone,";
}
if (Email.Checked == true)
{
d = "Email,";
}
Label1.Text = a;
Label2.Text = b;
Label3.Text = c;
Label4.Text = d;
string Query = ("SELECT" b c d "FROM Employee WHERE Employee_ID =" a);
}
What exactly is the issue you're running in to?
I would guess that you're having an issue running that query because it'll have a comma before FROM
. A better way to hold the fields you want to search on might be to push the values into a single array and then loop through the contents of the array and separate each by a comma. That way your list of fields can grow and shrink to any size without worrying about empty values. You also might want to consider wrapping the "a" value in single quotes (assuming you're reading in strings...)
Old code:
string Query = ("SELECT" b c d "FROM Employee WHERE Employee_ID =" a);
Result: *SELECT Address,Phone,Email,FROM Employee WHERE Employee_ID = Bob Jones*
New code:
string Query = "SELECT " + String.Join(", ", arrFields) + " FROM Employee WHERE Employee_ID = '" + a + "'"
Result: *SELECT Address, Phone, Email FROM Employee WHERE Employee_ID = 'Bob Jones'*
Is String concatenation what you are looking for?
Try using this:
string Query = String.Format("SELECT {0} {1} {2} FROM Employee WHERE Employee_ID ={3}",b,c,d,a);
精彩评论